DEV Community

Benjamin Mock
Benjamin Mock

Posted on

19 7

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

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;

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)