javascript 设置 cookie 一天后过期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32998471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting cookie to expire after one day
提问by user2278240
I have used this code I got from git. Its basically set up to set a cookie to display a popup on the first visit to the site only. However, I want it to only set it for 24 hours. So if someone comes back to the site in a day or two it will show again.
我已经使用了从 git 获得的这段代码。它基本上设置为设置 cookie 以仅在第一次访问该站点时显示弹出窗口。但是,我希望它只设置 24 小时。因此,如果有人在一两天内再次访问该站点,它将再次显示。
(function ($) {
'use strict';
$.fn.firstVisitPopup = function (settings) {
var $body = $('body');
var $dialog = $(this);
var $blackout;
var setCookie = function (name, value) {
var date = new Date(),
expires = 'expires=';
date.setTime(date.getTime() + 31536000000);
expires += date.toGMTString();
document.cookie = name + '=' + value + '; ' + expires + '; path=/';
}
var getCookie = function (name) {
var allCookies = document.cookie.split(';'),
cookieCounter = 0,
currentCookie = '';
for (cookieCounter = 0; cookieCounter < allCookies.length; cookieCounter++) {
currentCookie = allCookies[cookieCounter];
while (currentCookie.charAt(0) === ' ') {
currentCookie = currentCookie.substring(1, currentCookie.length);
}
if (currentCookie.indexOf(name + '=') === 0) {
return currentCookie.substring(name.length + 1, currentCookie.length);
}
}
return false;
}
var showMessage = function () {
$blackout.show();
$dialog.show();
}
var hideMessage = function () {
$blackout.hide();
$dialog.hide();
setCookie('fvpp' + settings.cookieName, 'true');
}
$body.append('<div id="fvpp-blackout"></div>');
$dialog.append('<a id="fvpp-close">✖</a>');
$blackout = $('#fvpp-blackout');
if (getCookie('fvpp' + settings.cookieName)) {
hideMessage();
} else {
showMessage();
}
$(settings.showAgainSelector).on('click', showMessage);
$body.on('click', '#fvpp-blackout, #fvpp-close', hideMessage);
};
})(jQuery);
回答by Barmar
Change:
改变:
date.setTime(date.getTime() + 31536000000);
to:
到:
date.setDate(date.getDate() + 1);
This adds 1 day to the date. The old code was adding 365 days.
这将在日期上增加 1 天。旧代码增加了 365 天。
回答by abo46n2
This is what I do in my projects which I find easier to understand. Just change the last number according to how many days you want to add to the current time, timestamp
:
这就是我在我的项目中所做的,我觉得这更容易理解。只需根据您要添加到当前时间的天数更改最后一个数字,即可timestamp
:
const timestamp = new Date().getTime(); // current time
const exp = timestamp + (60 * 60 * 24 * 1000 * 7)
60 minutes * 60 seconds * 24 hours * 1000 (for milliseconds) * 7 days
60分钟*60秒*24小时*1000(毫秒)*7天
or you could simply use 86400000
.
或者你可以简单地使用86400000
.