Subscribe

Vanilla JavaScript How many Days Between Two Dates

✍️

How to calculate the difference between two dates in JavaScript

21 May, 2020 Β· 1 min read

Today we will learn how to get the number of days between two dates in JavaScript.

Calculate date difference in days

First, we are going to define two date objects.

const date1 = new Date('12/25/2022');
const date2 = new Date();

Then we need to get the difference between these two dates.

const difference = date1.getTime() - date2.getTime();

The date difference is now in milliseconds, so we must convert it to days.

(1000 milliseconds _ (60 minutes _ 60 seconds) * 24 hours)

This will return the number of days between both dates:

const days = Math.ceil(difference / (1000 * 3600 * 24));
console.log(days + ' days to Christmas');

See the code example in this Codepen

See the result and calculate how many days are left until Christmas.

See the Pen Vanilla JavaScript Days Between Two Dates by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next πŸ“–

TypeORM viewEntity

30 Mar, 2022 Β· 5 min read

TypeORM viewEntity

The Record Utility Type in TypeScript

12 Mar, 2022 Β· 3 min read

The Record Utility Type in TypeScript

Join 1371 devs and subscribe to my newsletter