How would you go about determining how many minutes until midnight of the current day using javascript?
Asked
Active
Viewed 1.3k times
10
-
Maybe this post can help you: http://stackoverflow.com/questions/5847165/jquery-get-difference-between-two-dates – Gustavo Barrientos Dec 21 '11 at 00:24
-
Midnight according to the client's computer, or according to the server that sent the client the js? – JesseBuesking Dec 21 '11 at 00:26
-
@JesseB: server time, it's for console script – Pastor Bones Dec 21 '11 at 00:33
-
@Parson: All the answers below refer to client's midnight. You should calculate server time on the server – Dan Apr 03 '13 at 17:44
4 Answers
15
function minutesUntilMidnight() {
var midnight = new Date();
midnight.setHours( 24 );
midnight.setMinutes( 0 );
midnight.setSeconds( 0 );
midnight.setMilliseconds( 0 );
return ( midnight.getTime() - new Date().getTime() ) / 1000 / 60;
}
Will
- 18,657
- 7
- 46
- 48
-
I recommend kennebeck's or RobG's answer. Just not to repeat myself, I'm giving the link with problem explanation: http://stackoverflow.com/a/15792909/139361 – Dan Apr 03 '13 at 17:34
-
3
15
Perhaps:
function minsToMidnight() {
var now = new Date();
var then = new Date(now);
then.setHours(24, 0, 0, 0);
return (then - now) / 6e4;
}
console.log(minsToMidnight());
or
function minsToMidnight() {
var msd = 8.64e7;
var now = new Date();
return (msd - (now - now.getTimezoneOffset() * 6e4) % msd) / 6e4;
}
console.log(minsToMidnight())
and there is:
function minsToMidnight(){
var d = new Date();
return (-d + d.setHours(24,0,0,0))/6e4;
}
console.log(minsToMidnight());
or even a one-liner:
minsToMidnight = () => (-(d = new Date()) + d.setHours(24,0,0,0))/6e4;
console.log(minsToMidnight());
Konrad Pettersson
- 41
- 5
RobG
- 134,457
- 30
- 163
- 204
-
-
@quick007—because of the time that elapses between clicking the buttons. :-) – RobG Apr 21 '22 at 12:52
6
You can get the current timestamp, set the hours to 24,
and subtract the old timestamp from the new one.
function beforeMidnight(){
var mid= new Date(),
ts= mid.getTime();
mid.setHours(24, 0, 0, 0);
return Math.floor((mid - ts)/60000);
}
alert(beforeMidnight()+ ' minutes until midnight')
kennebec
- 98,993
- 30
- 103
- 125