Portekoi
Portekoi

Reputation: 1147

How to set multiple values with two differents expires dates

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?

Upvotes: 0

Views: 1181

Answers (2)

Portekoi
Portekoi

Reputation: 1147

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

Upvotes: 0

Jack L.
Jack L.

Reputation: 1335

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.

Upvotes: 2

Related Questions