DEV Community

loading...

πŸ“…πŸ“… How to compare Dates in JS (getting the difference in days)

Benjamin Mock
I'm Ben, a Frontend Developer from Germany working at ebay
・1 min read

Let's say we start with a date String and we want to calculate the difference in days to the current date.

  • First we need to convert the String to a Date
  • then we get today's date
  • and compare the two

So how do we convert a String to a Date? The constructor of Date does this for you. Just pass along the String like this:

const pastDate = new Date("2017-04-15")

Today's Date you can get with the empty constructor:

const today = new Date()

Now let's compare the two dates. For this, we will use the UNIX time. The UNIX time is the time passed in milliseconds since January 1st 1970 00:00:00.

const pastDate = new Date("2017-04-15")
const today = new Date()

const differenceInMs = today.getTime() - pastDate.getTime()

This gives us the difference in milliseconds. Let's convert it now to days. By dividing it through 1000 we'll get the difference in seconds. Dividing this by 60 gives us minutes. By another 60 gives us hours. And by another 24 gives us days.

const pastDate = new Date("2017-04-15")
const today = new Date()

const differenceInMs = today.getTime() - pastDate.getTime()
const differenceInDays = differenceInMs / 1000 / 60 / 60 / 24;

Discussion (0)