Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!