Search code examples
javascriptcookiesexpired-cookies

Cookie expiration date won't change.


I'm trying to create a cookie and set an expiration date but it stays as "Session". I'm using Google Chrome.

What am I doing wrong?

document.cookie = "savedTests=[{'id':12345678}];expires=" + date.toUTCString() + ";path=/" ;


Solution

  • Try This, Changed some layout for better understanding :

    var cookieName = 'savedTests';
    var cookieValue = [
    {'id':12345678}
    ];
    var cookieString = JSON.stringify(cookieValue);
    
    var addDays = 2;
    var newDate = new Date();
    newDate.setTime(newDate.getTime() + (addDays*24*60*60*1000));
    var expiresInTime = "expires="+ newDate.toUTCString();
    document.cookie = cookieName + "=" + cookieString + ";" + expiresInTime + ";path=/";
    

    Result : Result