Easy and right ways to calculate difference between two dates in Javascript.
Problem
We are given two dates and we have to print the difference between those two dates in days. Since we are given two valid dates, half of our problem is already gone and we have not started yet.
Get started
Calculate number of days - simple and plain.
|
|
Date in Javascript is in millseconds since 1970. So the difference between two date objects is a big millisecond number. We just convert that to days.
1 day = Y ms / (1000 milliseconds in 1 second _ 3600 seconds in 1 hour _ 12 hours in a day)
Consider UTC
Dates can be from different time zones or have day light savings at different times. So, it may be a good idea to convert them to UTC and find the difference between UTC dates.
|
|
Be careful about the subtraction
If you are not sure about which one of the dates is more recent, you can use math functions to find absolute difference. While you are at it, also use a different Math
function to round off to nearest (lower) whole number.
|
|