Borislav Hadzhiev
Mon Mar 07 2022·2 min read
Photo by Alexandre Perotto
To get the difference between 2 dates in days:
function getDayDiff(startDate: Date, endDate: Date): number { const msInDay = 24 * 60 * 60 * 1000; return Math.round(Math.abs(Number(endDate) - Number(startDate)) / msInDay); } // 👇️ 10 console.log(getDayDiff(new Date('2022-03-17'), new Date('2022-03-27'))); // 👇️ 30 console.log(getDayDiff(new Date('2022-04-17'), new Date('2022-05-17')));
We created a reusable function which returns the number of days between 2 dates.
The msInDay
variable stores the number of milliseconds there are in a day.
Date
object to a number
, you get back a timestamp that represents the milliseconds elapsed between January 1st, 1970 and the given date.It is the same as calling the getTime()
method on both of the Date
objects
to get a timestamp in milliseconds.
function getDayDiff(startDate: Date, endDate: Date): number { const msInDay = 24 * 60 * 60 * 1000; // 👇️ explicitly calling getTime() return Math.round( Math.abs(endDate.getTime() - startDate.getTime()) / msInDay, ); } // 👇️ 10 console.log(getDayDiff(new Date('2022-03-17'), new Date('2022-03-27'))); // 👇️ 30 console.log(getDayDiff(new Date('2022-04-17'), new Date('2022-05-17')));
This might be the more clear and explicit approach for readers of your code.
We used the Math.abs function to handle a scenario where we subtract a greater timestamp from a smaller one.
The Math.abs
function returns the absolute value of a number. In other words,
if the number is positive, the number is returned and if the number is negative,
the negation of the number is returned.
console.log(Math.abs(-5)); // 👉️ 5 console.log(Math.abs(5)); // 👉️ 5
We passed the value to the Math.round function to round to the nearest integer to deal with Daylight saving time.
Here are some examples of how the Math.round
function works.
console.log(Math.round(2.49)); // 👉️ 2 console.log(Math.round(2.5)); // 👉️ 3
The function rounds the number up or down to the nearest integer.
0.5
, it gets rounded to the next higher absolute value.If the number is positive and its fractional portion is less than 0.5
, it gets
rounded to the lower absolute value.