What is the best way to calculate the time passed since (last) midnight in ms?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Simpler to write, if you don't mind creating two dates.
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:
10 * 60 * 60 * 1000
msSecond 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:
Third is my personal pitfall you could possibly experience
Consider the following code:
msSinceMidnight
is always0
as the object is changed during computation before the substraction operationAt last, this code works:
Create a new date using the current day/month/year, and get the difference.
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: