10

How would you go about determining how many minutes until midnight of the current day using javascript?

Pastor Bones
  • 7,183
  • 3
  • 36
  • 56

5 Answers5

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
    consider using `midnight.setHours(24, 0, 0, 0)` – rabudde Jan 27 '15 at 20:22
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());
RobG
  • 142,382
  • 31
  • 172
  • 209
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
2

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
donohoe
  • 13,867
  • 4
  • 37
  • 59
H K
  • 1,062
  • 8
  • 10
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