Search code examples
javascriptcookies

How can I set a cookie with expire time?


I am setting a cookie with JavaScript and it is working fine but it is not taking the expire time I am giving. It keeps on taking session value regardless of what I give, below is the code which I took from here

var now = new Date();
var time = now.getTime();
var expireTime = time + 1000*60;
now.setTime(expireTime);
var tempExp = 'Wed, 31 Oct 2012 08:50:17 GMT';
document.cookie = aaa+'='+sStr+';expires='+now.toGMTString()+';path=/';

I tried giving hard-coded value but still it is showing expire as session in chrome dev tool

var tempExp = 'Wed, 31 Oct 2012 08:50:17 GMT';
document.cookie = aaa+'='+sStr+';expires='+tempExp+';path=/';

Any idea what I am doing wrong?


Solution

  • I've set the time to 1000*36000.

    function display() { 
      var now = new Date();
      var time = now.getTime();
      var expireTime = time + 1000*36000;
      now.setTime(expireTime);
      document.cookie = 'cookie=ok;expires='+now.toUTCString()+';path=/';
      //console.log(document.cookie);  // 'Wed, 31 Oct 2012 08:50:17 UTC'
    }
    

    expiration