Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

113
Visualizações
Setting an expiration date with javaScript is not working correctly
  const cookieButton = document.getElementById('store-cookie')

  cookieButton.addEventListener('click', e => {
    const input = document.getElementById('fav-cookie').value
    let date = new Date()
    let minutes = 30;
    date.setTime(date.getTime() + (minutes * 60 * 1000))
    document.cookie = `favCookie=${input}; expires=${date.toTimeString()};`
  })

I'm working on a coding problem meant to be only used in javaScript. It requires to make a cookie with the value of an input field (on a linked html), on pressing a button. The bonus for this question requires the cookie to expire after 30 minutes it's created. Currently, this code is just saving the favCookie=input; but it is not adding an expiration date. Any help would be appreciated!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You could create 2 date variables, on the second use the setMinutes method to add 30mins to the current time then create a function to clear/change the value if and when the current date/time equals the new date.

 var expire = new Date();
 expire.setMinutes( expire.getMinutes() + 30 );
about 4 years ago · Juan Pablo Isaza Relatório

0

Use toUTCString() instead.

 const cookieButton = document.getElementById('store-cookie');
 cookieButton.addEventListener('click', e => {
    const input = document.getElementById('fav-cookie').value;
    const date = new Date();
    date.setTime(date.getTime() + (30* 60 * 1000));
   document.cookie = `favCookie=${input}; expires=${date.toUTCString()};`;
 });

Cookies are always tricky. I believe it is because your timestamp should be formatted like so:

2021-10-23T20:32:38.000Z

Instead you currently have set by toTimeString()

22:29:12 GMT+0200 (Central European Summer Time)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda