[英]How to realize “is next day” verification in javascript?
我在javascript本地存储中有状态,例如var count = 0;
变量。
一些函数会更改此变量:
function foo () {
this.count++;
localStorage.setItem('COUNT', this.count);
}
在重新加载页面上,我从本地存储恢复此值
function restore() {
this.count = localStorage.getItem('COUNT');
}
问题-在每个新的一天(按用户的时区)使变量count
无效。 因此,我需要为此“验证”。
因此,我开始存储上次访问,并根据每个请求的当前日期进行检查。 但这不适用于我的GMT + 04:00时区:第二天到了,但没有发生nullify。
let lastVisitTimestamp = localStorage.getItem(TRACKING_LAST_VISIT_STORAGE_ID);
if (!lastVisitTimestamp) {
this.count = 0;
localStorage.setItem(TRACKING_LAST_VISIT_STORAGE_ID, (new Date()).getTime());
return;
}
let currentDate = new Date();
currentDate.setHours(0,0,0,0);
let previousDate = new Date(parseInt(lastVisitTimestamp));
previousDate.setHours(0,0,0,0);
if (currentDate.getTime() === previousDate.getTime()) {
this.count = localStorage.getItem('COUNT');
} else {
this.count = 0;
localStorage.setItem(TRACKING_LAST_VISIT_STORAGE_ID, currentDate.getTime());
}
我应该改变什么?
我解决了这个问题。 需要操作日期字符串,而不是时间戳。 日期字符串可以通过以下方式获取:
function getCurrentDateString() {
let currentDate = new Date();
return new Date(currentDate.getTime() - (currentDate.getTimezoneOffset() * 60000)).toJSON().slice(0,10);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.