How would you go about determining how many minutes until midnight of the current day using javascript?
Asked
Active
Viewed 1.5k 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
5 Answers
16
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
- 19,661
- 7
- 47
- 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
- 47
- 1
- 5

RobG
- 142,382
- 31
- 172
- 209
-
-
1@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
- 102,654
- 32
- 106
- 127
0
Posting this as an alternative solution which works for any hour of the day.
const timeUntilHour = (hour) => {
if (hour < 0 || hour > 24) throw new Error("Invalid hour format!");
const now = new Date();
const target = new Date(now);
if (now.getHours() >= hour)
target.setDate(now.getDate() + 1);
target.setHours(hour);
target.setMinutes(0);
target.setSeconds(0);
target.setMilliseconds(0);
return target.getTime() - now.getTime();
}
const millisecondsUntilMidnight = timeUntilHour(24);
const minutesUntilMidnight = millisecondsUntilMidnight / (60 * 1000);

nullmn
- 557
- 2
- 7
- 19