0

I'm trying to set cookie in javascript with two values. Each of theses have a different expiration date.

For example :

var now = new Date();
now.setDate( now.getDate() + 2 );
document.cookie = "bar=foo;";
document.cookie = "expires=" + now.toUTCString() + ";"

now = new Date();
now.setDate( now.getDate() + 30 );
document.cookie = "foo=bar;";
document.cookie = "expires=" + now.toUTCString() + ";"

Is it correct? How to set another value with an expiration date for 30 days for example?

Portekoi
  • 1,087
  • 2
  • 22
  • 44

2 Answers2

2

I think that approach is correct.

Based on: How can I set a cookie to expire after x days with this code I have? :

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

Note, that setTime() and getTime() work on milliseconds. And a few words from me: as javascript's Date sucks, I recommend using moment.js library when working with dates, it's brilliant.

Community
  • 1
  • 1
Jack L.
  • 1,257
  • 2
  • 17
  • 37
0

Ok, i found my reply here with the function "setCookie". I've specify differents values and it's working. http://www.w3schools.com/js/js_cookies.asp

Portekoi
  • 1,087
  • 2
  • 22
  • 44