简体   繁体   中英

Javascript cookies - setting a cookie to expire after 12hours

I am in desperate need of some help. I need to set a javascript cookie to expire after 12hours.

I am using the following Javascript code:

  function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*12*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;
   }
  function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";

    var 1 = $(this).attr('name');
setCookie("2", 3, 30);
var Get4=$(this).attr('4');
var Get5=$(this).attr('5');
var Get6=$(this).attr('6');
$("#6").val(Get6);
$("#4").val(Get4);
$("#5").val(Get5);

The 2 main things I need to know is what the following code does and how it works

d.setTime(d.getTime() + (exdays*12*60*60*1000)
setCookie("2", 3, 30);

And what the 30 means in this setCookie code. Is the 30 for 30days,30minutes or 30hours?

Please do not worry about the numbers they are just place holders for my question.

Any assistance will be greatly appreciated. Thanking you in advance. Regards.

The calculation d.getTime() + (exdays*12*60*60*1000) is to find the absolute time when the cookie should expire. Time in Javascript is measured by milliseconds from a specific date, which means that to jump ahead by 12 hours, you add 12 hours' worth of milliseconds to the current time ( new Date().getTime() .

Therefore, to make the cookie expire 12 hours in the future, you need to add 12*60*60*1000 to the current time in millis:

var d = new Date();
d.setTime(d.getTime() + 12*60*60*1000);
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;

will create the cookie value that you're looking for.

The 30 is the exDays parameter, which was supposed to be a number of days to expire in. As I mentioned in the comment, since the number of days was multiplied by 12 and not 24 , that code was incorrect anyhow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM