How can JS set the validity period of cookie to 24 o'clock on the same day and pop up the welcome login interface

  • 2021-07-09 06:37:04
  • OfStack

Simply write, according to the specified parameters Deadline format time for testing, if there are some imprecise place also please point out.


//  Settings cookie Expires at the specified time point of the day and prompts 
function setCookie(name,value,Deadline,callback){
//  Gets the current date object 
var curDate = new Date();
//  Gets the timestamp corresponding to the current date 
var curTime = curDate.getTime();
//  Gets the timestamp of the specified time 
var endTime = convertTime(curDate,Deadline);
//  Calculates the time difference between the specified time and the current time 
var disTime = endTime - curTime;
//  Settings cookie Expired time 
document.setCookie = name + '=' + value + ';expires=' + disTime;
//  Executes a callback after the specified time has arrived 
setTimeout(callback,disTime);
}
setCookie('name','value','24:00:00',function(){
alert('cookie Expired ');
});
//  Gets the timestamp of the specified time 
function convertTime(nowDate,Deadline){
//  Partition parameter Deadline
var _dateArr = Deadline.split(':');
//  Get the corresponding hours, minutes and seconds in the parameters respectively 
var hours = parseInt(_dateArr[0]);
var minutes = parseInt(_dateArr[1]);
var seconds = parseInt(_dateArr[2]);
//  Set the corresponding time and second 
nowDate.setHours(hours); 
nowDate.setMinutes(minutes); 
nowDate.setSeconds(seconds);
//  Gets the number of milliseconds corresponding to the specified time division and second in the current day 
var result = Date.parse(nowDate);
return result;
}

Additional:


function setCookie(name,value,days){// Settings cookie
var d = new Date();
d.setTime(d.getTime() + (days*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = name + "=" + value + "; " + expires;
}

Related articles: