DEV Community

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

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

16 1

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

Neon image

Set up a Neon project in seconds and connect from a Next.js application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Dive into this insightful write-up, celebrated within the collaborative DEV Community. Developers at any stage are invited to contribute and elevate our shared skills.

A simple "thank you" can boost someone’s spirits—leave your kudos in the comments!

On DEV, exchanging ideas fuels progress and deepens our connections. If this post helped you, a brief note of thanks goes a long way.

Okay