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()