Quantcast
Channel: How do I get the difference between two Dates in JavaScript? - Stack Overflow
Viewing all articles
Browse latest Browse all 20

Answer by Dan for How do I get the difference between two Dates in JavaScript?

$
0
0

JavaScript perfectly supports date difference out of the box

https://jsfiddle.net/b9chris/v5twbe3h/

var msMinute = 60*1000,     msDay = 60*60*24*1000,    a = new Date(2012, 2, 12, 23, 59, 59),    b = new Date("2013 march 12");console.log(Math.floor((b - a) / msDay) +' full days between'); // 364console.log(Math.floor(((b - a) % msDay) / msMinute) +' full minutes between'); // 0

Now some pitfalls. Try this:

console.log(a - 10); // 1331614798990console.log(a + 10); // mixed string

So if you have risk of adding a number and Date, convert Date to number directly.

console.log(a.getTime() - 10); // 1331614798990console.log(a.getTime() + 10); // 1331614799010

My fist example demonstrates the power of Date object but it actually appears to be a time bomb


Viewing all articles
Browse latest Browse all 20

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>