Have you ever tried calculating the number of days between two dates in JavaScript without a library? Well, here's how
Short answer:
const firstDate = new Date("05/10/2022") // 10th May, 2022
const secondDate = new Date() // today, 14th May, 2022
const millisecondsDiff = secondDate.getTime() - firstDate.getTime()
const daysDiff = Math.round(
millisecondsDiff / (24 * 60 * 60 * 60)
)
Long answer
To find the difference between two dates, you first need to get the time value in milliseconds. You get this using the getTime
method on the Date
instance:
const firstDate = new Date("05/10/2022") // 10th May, 2022
const secondDate = new Date() // today, 14th May, 2022
const firstDateInMs = firstDate.getTime()
const secondDateInMs = secondDate.getTime()
The millisecond value is a number on which you can then perform arithmetic operations like subtractions.
The next step is finding the difference between both dates:
const differenceBtwDates = secondDateInMs - firstDateInMs
console.log(differenceBtwDates)
// 351628869
Now, you have the difference in milliseconds between both dates. This is where you convert the milliseconds to days. How to do that?
First, you get the equivalence of 1 day (24 hours) in milliseconds. Here's how:
const aDayInMs = 24 * 60 * 60 * 1000
console.log(aDayInMs)
// 86400000
- 24 stands for 24 hours
- 60 stands for 60 minutes, which makes an hour, thereby converting 24 hours to minutes
- the next 60 stands for 60 seconds, which makes a minute
- and 1000 stands for 1000 milliseconds, which makes a second
Now that you have the milliseconds value for a day, you can use it to determine how many days the difference between the dates are.
If 86400000
(aDayInMs
) milliseconds makes a day, then, 351628869
(differenceBtwDates
) milliseconds makes:
const daysDiff = differenceBtwDates / aDayInMs
console.log(daysDiff)
// 4.0782153125
As it returns a floating number, you can round it up with Math.round()
:
const daysDiff = Math.round(differenceBtwDates / aDayInMs)
console.log(daysDiff)
// 4
Comparing May 10th and May 14th, it is a 4-day difference.
Here's the full code:
const firstDate = new Date("05/10/2022") // 10th May, 2022
const secondDate = new Date() // today, 14th May, 2022
const firstDateInMs = firstDate.getTime()
const secondDateInMs = secondDate.getTime()
const differenceBtwDates = secondDateInMs - firstDateInMs
const aDayInMs = 24 * 60 * 60 * 1000
const daysDiff = Math.round(differenceBtwDates / aDayInMs)
console.log(daysDiff)
// 4
firstDate
and secondDate
can be any dates at all. I used May 10th and 14th for explanation purposes.
Top comments (0)