zuuuuuuuu
zuuuuuuuu

Reputation: 15

jQuery cookie expires time is not correctly

I set cookie using jquery. but consoleLog date and expire date is not same.

function setCookie() {   
const date = new Date(); //Tue Oct 22 2019 17:45:53 GMT+0900 (한국 표준시)   
const expires = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59); // Tue Oct 22 2019 23:59:59 GMT+0900 (한국 표준시) 
$.cookie('AAA', '', { expires }); 

}

But expire date is 2019-10-22T14:59:59.000Z time is not same. I found this issue in Chrome. Your help is much appreciated!

Upvotes: 1

Views: 767

Answers (1)

Bilal Siddiqui
Bilal Siddiqui

Reputation: 3629

Simple answer

When you put a non-UTC date into the expires, then the javascript automatically convert the date to a GMT.

JavaScript Cookie expires time must be GMT/UTC

You may use following to have an UTC date that ends at 23:59:59

const date = new Date(); 
const expires = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59));
console.log(expires.toUTCString());

Update As per OP asked in comment to provide another approach so that he need not to use getFullYear, getMonth etc. methods. Here is how one can convert currentDate into UTC that ends at 23:59:59 without using Date.UTC and year/month functions:

  var curDate = new Date();
  curDate.setUTCHours(23);
  curDate.setUTCMinutes(59);
  curDate.setUTCSeconds(59);
  console.log(curDate.toISOString())

Upvotes: 1

Related Questions