Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda