Reputation: 7351
How would you go about determining how many minutes until midnight of the current day using javascript?
Upvotes: 11
Views: 15711
Reputation: 607
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);
Upvotes: 0
Reputation: 1232
Here's a one-liner to get milliseconds until midnight
new Date().setHours(24,0,0,0) - Date.now()
And for the minutes until midnight, we divide that by 60 and then by 1000
(new Date().setHours(24,0,0,0) - Date.now()) / 60 / 1000
Upvotes: 2
Reputation: 147403
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());
Upvotes: 17
Reputation: 104780
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')
Upvotes: 7
Reputation: 20235
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;
}
Upvotes: 17