Skip to content Skip to sidebar Skip to footer

Determine Minutes Until Midnight

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

Solution 1:

functionminutesUntilMidnight() {
    var midnight = newDate();
    midnight.setHours( 24 );
    midnight.setMinutes( 0 );
    midnight.setSeconds( 0 );
    midnight.setMilliseconds( 0 );
    return ( midnight.getTime() - newDate().getTime() ) / 1000 / 60;
}

Solution 2:

Perhaps:

functionminsToMidnight() {
  var now = newDate();
  var then = newDate(now);
  then.setHours(24, 0, 0, 0);
  return (then - now) / 6e4;
}

console.log(minsToMidnight());

or

functionminsToMidnight() {
  var msd = 8.64e7;
  var now = newDate();
  return (msd - (now - now.getTimezoneOffset() * 6e4) % msd) / 6e4;
}

console.log(minsToMidnight())

and there is:

functionminsToMidnight(){
  var d = newDate();
  return (-d + d.setHours(24,0,0,0))/6e4;
}

console.log(minsToMidnight());

or even a one-liner:

minsToMidnight = () => (-(d = newDate()) + d.setHours(24,0,0,0))/6e4;

console.log(minsToMidnight());

Solution 3:

You can get the current timestamp, set the hours to 24,

and subtract the old timestamp from the new one.

functionbeforeMidnight(){
    var mid= newDate(), 
    ts= mid.getTime();
    mid.setHours(24, 0, 0, 0);
    returnMath.floor((mid - ts)/60000);
}

alert(beforeMidnight()+ ' minutes until midnight')

Solution 4:

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 devide that by 60 and then by 1000

(newDate().setHours(24,0,0,0) - Date.now()) / 60 / 1000

Post a Comment for "Determine Minutes Until Midnight"