Determine minutes until midnight

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;
}

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')


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());

Tags:

Javascript