Javascript date.setSeconds working as expected in Debugger but not in script

Viewed 864

I have a function that sets a cookie as follows:

function createCookieWithDuration(name, value, duration) {
    const date = new Date();
    console.log(`date now: ${date}`);
    date.setSeconds(date.getSeconds() + duration);
    console.log(`adjusted date by ${duration} seconds: ${date}`);
    document.cookie = `${name}=${value}; expires=${date}; path=/`;
}

Now, if I do this line for line in the debugger it works as expected: enter image description here

But when I let the script run and log to the console I get 3 minutes added on as well as the seconds:

enter image description here

Is there a weird javascript timing thing that I'm missing here?

2 Answers

Use this code, but make sure that duration is in miliseconds, so if you want to add 2 seconds you need to pass 2000, or if you're passing seconds just add duration * 1000 in code.

function createCookieWithDuration(name, value, duration) {
    const date = new Date();
    console.log(`date now: ${date}`);
    const newDate = new Date(date.getTime() + duration);
    console.log(`adjusted date by ${duration}: ${newDate}`);
    document.cookie = `${name}=${value}; expires=${newDate}; path=/`;
}

Clearly setSeconds() refers to current time. You may use alert() to see even bigger differences. However, the following will work as you expect: Replace:

date.setSeconds(date.getSeconds() + duration);

With:

    date.setHours(date.getHours(), date.getMinutes(), date.getSeconds()+ duration, 0);

Note that I zero milliseconds, you may handle it as you like. see working example jsfiddle

Related