Vanilla JavaScript Days Between Two Dates

— 2 minute read

permalink

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

Calculate days between two dates permalink

First we are going to define two date objects.

var date1 = new Date('12/25/2020');
var date2 = new Date();

The we need to know the difference between these two dates

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

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');

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! permalink

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