Juan Jardim Juan Jardim - 1 year ago 209
Javascript Question

Best Way to detect midnight and reset data

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.

Answer Source

Use moment().format("h:mm:ss") that returns time in a h:mm:ss format.

var midnight = "0:00:00";
var now = null;

setInterval(function () {
    now = moment().format("h:mm:ss");
    if (now === midnight) {
}, 1000);


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');

So, just do:

   moment("24:00:00", "hh:mm:ss").diff(moment(), 'seconds')

function midnightTask() {
  /* do something */