We have always run into a situation when we need to calculate the difference between two dates, but there is no concrete method that gives us the number of days accurately.
This is the function that is used widely.
// Old Function function date_diff(date1, date2){ var one_day = 1000 * 3600 * 24; var time_diff = Math.abs(date2.getTime() - date1.getTime()); var days = time_diff / one_day; return Math.ceil(days); }
The above function does calculate the number of days but uses Math.ceil() which doesnt provide the exact days as there is a decimal error.
For Example, when we try to find the difference between two dates 1944/01/01 and 2019/03/06, on line 5, the value of days is 27458.041666666668 which needs to be adjusted with a Math.ceil() or Math.floor() which might always throw off the final answer by 1 day. This is because dates don't account for DST(Daylight Saving Time) changes.
To overcome the above situation, we can use the following refined function.
function date_diff(date1, date2){ var one_day = 1000 * 3600 * 24; const utc1 = Date.UTC( date1.getFullYear(), date1.getMonth(), date1.getDate() ); const utc2 = Date.UTC( date2.getFullYear(), date2.getMonth(), date2.getDate() ); var days = (utc2 - utc1) / one_day; return Math.abs(days); }
In the above solution the value of days on line 13 is 27458 when we try to find the difference between the same dates 1944/01/01 and 2019/03/06.
The refined solution first normalizes the two given dates to UTC, and then calculates the difference between the two UTC dates. The good thing about UTC is that UTC time never observes DST. Thus, we get an accurate number of days between the two dates.