我一直在开发一个网络应用程序仪表板,我想知道如何检测午夜,以便使用 jquery 或 momentjs 重置一些包含前一天数据的数组。
最佳答案
使用 moment().format("h:mm:ss")
以 h:mm:ss
格式返回时间。
var midnight = "0:00:00";
var now = null;
setInterval(function () {
now = moment().format("H:mm:ss");
if (now === midnight) {
alert("Hi");
}
$("#time").text(now);
}, 1000);
更好的方法是计算到午夜的秒数。使用 MomentJS,这非常简单且易于阅读:
// returns the number of seconds until next midnight
moment("24:00:00", "hh:mm:ss").diff(moment(), 'seconds');
所以,就这样做:
setTimeout(
midnightTask,
moment("24:00:00", "hh:mm:ss").diff(moment(), 'seconds')
);
function midnightTask() {
/* do something */
}
关于javascript - 检测午夜和重置数据的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26387052/