Home > OS >  Setting an expiration date with javaScript is not working correctly
Setting an expiration date with javaScript is not working correctly

Time:10-24

  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!

CodePudding user response:

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 );

CodePudding user response:

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)

  • Related