If I have two dates, how can I use JavaScript to get the difference between the two dates in minutes?
相关问题
- 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?
A simple function to perform this calculation:
That's should show the difference between the two dates in minutes.
You may checkout this code:
or
var diffMins = Math.floor((...
to discard seconds if you don't want to round minutes.This problem is solved easily with moment.js, like this example:
var difference = mostDate.diff(minorDate, "minutes");
The second parameter can be changed for another parameters, see the moment.js documentation.
e.g.: "days", "hours", "minutes", etc.
http://momentjs.com/docs/
The CDN for moment.js is available here:
https://cdnjs.com/libraries/moment.js
Thanks.
EDIT:
mostDate and minorDate should be a moment type.
Here's some fun I had solving something similar in node.
You can see it in action at https://repl.it/@GioCirque/TimeSpan-Formatting
Subtracting 2 Date objects gives you the difference in milliseconds, e.g.:
Math.abs
is used to be able to use the absolute difference (sonew Date('2011/10/09 00:00') - new Date('2011/10/09 12:00')
gives the same result).Dividing the result by 1000 gives you the number of seconds. Dividing that by 60 gives you the number of minutes. To round to whole minutes, use
Math.floor
orMath.ceil
:In this example the result will be 720