-1

Set a cookie expire after 3 hours

I have this JavaScript code:

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

How can I make the cookie expire after 3 hours?

Pierre
  • 18,643
  • 4
  • 41
  • 62
  • the code is misleading ... that cookie would expire `days * 2 hours` - so, calling the function like `createCookie("blah", "fred", 1.5) would do it – Jaromanda X Jul 02 '15 at 12:27
  • change `days*2*60*60*1000` to `days*24*60*60*1000` and then call the function as createCookie('name', 'value',0.125). –  Jul 02 '15 at 12:29
  • possible duplicate of [Set a cookie expire after 2 hours](http://stackoverflow.com/questions/19068812/set-a-cookie-expire-after-2-hours) – Midhun Murali Jul 02 '15 at 12:32

3 Answers3

0

1st Method

Modify function to be:

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

And you will use createCookie(...,...,3);

2nd Method

Or using the following prototype:

Date.prototype.addHours= function(h){
    this.setHours(this.getHours()+h);
    return this;
}

And the following createCookie function:

  function createCookie(name,value,date) {
        if(date){
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";}

And you will use createCookie(...,...,new Date().addHours(3));

Razvan Dumitru
  • 11,815
  • 5
  • 34
  • 54
0

Your code seems to save the cookie for only 1/12 of a day.

days*2*60*60*1000

should be

days*24*60*60*1000

So when you want 3 hours you need to save the cookie for 1/8 of a day 24/8

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=/";
}

createCookie("name", "3 hours", 1/8);
Sebastian Nette
  • 7,364
  • 2
  • 17
  • 17
0

Hope it should be like this

function createCookie(name,value,hours) {
if (hours) {
    var date = new Date();
    date.setTime(date.getTime()+(hours*60*60*1000));        
    var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";}
Midhun Murali
  • 2,089
  • 6
  • 28
  • 49