检测午夜和重置数据的最佳方法 [英] Best Way to detect midnight and reset data

查看:113
本文介绍了检测午夜和重置数据的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在开发Web应用程序仪表板,我想知道如何检测到午夜,以便使用jquery或momentjs重置某些包含前一天数据的数组.

I've been developing a web application Dashboard and I was wondering how to detect that is midnight in order to reset some arrays that contains datas from the previous day using jquery or 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);

JSFIDDLE

更好的方法是计算直到午夜的秒数.这非常简单,使用MomentJS易于阅读:

A better way would be to compute the seconds until midnight. This is very simple and human readable using 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 */
}

JSFIDDLE

这篇关于检测午夜和重置数据的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆