Khanh Pham Khanh Pham - 5 months ago 10
Javascript Question

jquery library know when new day is coming

I wonder how can detect or know when new day is coming by using

jquery
or
others jquery library
.

For examples:

Assume, right now is
2016/06/23 23:59:50
. And when
second
come to
2016/06/24 00:00:00
,
jquery
can detect an
event
.

I know we can use
setTimeOut
or
setInterval
and check every seconds when new day is coming.

But i don't want to use these methods above, what methods of jquery do we detect ?

Answer

There's no automatic event that's triggered when the date changes. What you can do is calculate the time until the date changes, and use setTimeout to run a function when that happens.

var now = new Date;
var midnight = new Date(now.getYear(), now.getMonth(), now.getDate() + 1);
setTimeout(function() {
    alert("It's tomorrow!");
}, midnight.getTime() - now.getTime());

The arguments to new Date() are the components of the date and time. Leaving out the time arguments defaults them all to 0. So adding 1 to the date and omitting the time will return the time of the next midnight.