Hi I need to set this cookie for a month
I just need this feature to expire after a month, can anyone tell me how to do this?
function _saveUserPreference() {
// Set the cookie expiry to one year after today.
var expiryDate = new Date();
expiryDate.setFullYear(expiryDate.getFullYear() + 1);
document.cookie = cookieName + '=y; expires=' + expiryDate.toGMTString();
}
+3
source to share
2 answers
function _saveUserPreference(){
var montharr = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
expiryDate = new Date(),
year = expiryDate.getFullYear(),
month = expiryDate.getMonth(),
date = expiryDate.getDate();
var newMonth, newYear;
expiryDate.setMonth(month+1);
newMonth = expiryDate.getMonth();
newYear = expiryDate.getFullYear();
// when expiryDate is 2014-01-31, setMonth(m+1),then expiryDate is 2014-03-03 or 2014-03-02
if(newMonth - month > 1 ){
if( isLeapYear(year) && newMonth === 2 ){
expiryDate.setDate(29);
expiryDate.setMonth(1);
}else{
expiryDate.setDate(montharr[newMonth-1]);
expiryDate.setMonth(newMonth-1);
}
}
document.cookie = cookieName + '=y; expires=' + expiryDate.toGMTString();
// if you mean a month to 30 days
/*var now = new Date(),
milliSeconds = now - 0 + 30 * 24 * 3600 * 1000,
expiryDate = new Date(milliSeconds);
document.cookie = cookieName + '=y; expires=' + expiryDate.toGMTString();*/
}
function isLeapYear(year){
if( year%4 === 0 && year%100 !== 0 ){
return true;
}
if( year%100 === 0 && year%400 === 0 ){
return true;
}
return false;
}
0
source to share