How to calculate ms since midnight in Javascript

2019-01-19 10:11发布

What is the best way to calculate the time passed since (last) midnight in ms?

7条回答
劫难
2楼-- · 2019-01-19 10:51
var today = new Date();
var d = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0, 0); 

var difference = today.getTime() - d.getTime();
查看更多
仙女界的扛把子
3楼-- · 2019-01-19 10:53

Simpler to write, if you don't mind creating two dates.

var msSinceMidnight= new Date()-new Date().setHours(0,0,0,0);
查看更多
爷、活的狠高调
4楼-- · 2019-01-19 10:59

Many answers except RobG's (recommended answer), Kolink's and Lai's are wrong here

Let's look closer together


First mistake

OptimusCrime and Andrew D. answers:

As Mala sugested, if the daylight saving correction was applied the nearest midnight, we get incorrect value. Let's debug:

  1. Suppose it's last Sunday of March
  2. The time is fixed at 2 am.
  3. If we see 10 am on the clock, there's actually 11 hours passed from midnight
  4. But instead we count 10 * 60 * 60 * 1000 ms
  5. The trick is played when midnight happens in different DST state then current

Second mistake

kennebeck's answer:

As RobG wrote, the clock can tick if you get the system time twice. We can even appear in different dates sometimes. You can reproduce this in a loop:

for (var i = 0; true; i++) {
    if ((new Date()).getTime() - (new Date()).getTime()) {
        alert(i); // console.log(i);  // for me it's about a 1000
        break;
    }
}

Third is my personal pitfall you could possibly experience

Consider the following code:

var d = new Date(),
    msSinceMidnight = d - d.setHours(0,0,0,0);

msSinceMidnight is always 0 as the object is changed during computation before the substraction operation


At last, this code works:

var d = new Date(),
    msSinceMidnight = d.getTime() - d.setHours(0,0,0,0);
查看更多
可以哭但决不认输i
5楼-- · 2019-01-19 11:05

Create a new date using the current day/month/year, and get the difference.

var now = new Date(),
    then = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate(),
        0,0,0),
    diff = now.getTime() - then.getTime(); // difference in milliseconds
查看更多
Juvenile、少年°
6楼-- · 2019-01-19 11:07
var d=new Date();
// offset from midnight in Greenwich timezone
var msFromMidnightInGMT=d%86400000;
// offset from midnight in locale timezone
var msFromMidnightLocale=(d.getTime()-d.getTimezoneOffset()*60000)%86400000;
查看更多
爷的心禁止访问
7楼-- · 2019-01-19 11:10

Seconds since midnight would simply be to display the time, but instead of using hours:minutes:seconds, everything is converted into seconds.

I think this should do it:

var now = new Date();    
var hours = now.getHours()*(60*60);
var minutes = now.getMinutes()*60;
var seconds = now.getSeconds();

var secSinceMidnight = hours+minutes+seconds;
查看更多
登录 后发表回答