Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine minutes until midnight

Tags:

javascript

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

like image 778
Pastor Bones Avatar asked Dec 21 '11 00:12

Pastor Bones


2 Answers

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());
like image 73
RobG Avatar answered Oct 27 '22 12:10

RobG


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

like image 28
kennebec Avatar answered Oct 27 '22 13:10

kennebec