DEV Community

Cover image for Vanilla JavaScript Days Between Two Dates
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Vanilla JavaScript Days Between Two Dates

Today we are solving the issues on how to get the number of days between two dates in JavaScript.

Calculate days between two dates

First we are going to define two date objects.

var date1 = new Date('12/25/2020');
var date2 = new Date();
Enter fullscreen mode Exit fullscreen mode

The we need to know the difference between these two dates

var difference = date1.getTime() - date2.getTime();
Enter fullscreen mode Exit fullscreen mode

This result is now in milliseconds so we have to convert it to days.

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

var days = Math.ceil(difference / (1000 * 3600 * 24));
console.log(days + ' days to Christmas');
Enter fullscreen mode Exit fullscreen mode

See the result and how many days till Christmas in this Codepen.

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

Top comments (0)