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 Jpsy for How do I get the difference between two Dates in JavaScript?

$
0
0

Many answers here are based on a direct subtraction of Date objects like new Date(…) - new Date(…). This is syntactically wrong. Browsers still accept it because of backward compatibility. But modern JS linters will throw at you.

The right way to calculate date differences in milliseconds is new Date(…).getTime() - new Date(…).getTime():

// Time difference between two dateslet diffInMillis = new Date(…).getTime() - new Date(…).getTime()

If you want to calculate the time difference to now, you can just remove the argument from the first Date:

// Time difference between now and some datelet diffInMillis = new Date().getTime() - new Date(…).getTime()

Viewing all articles
Browse latest Browse all 20

Trending Articles