Explain Codes LogoExplain Codes Logo

How to calculate the number of days between two dates?

javascript
date-objects
time-zones
date-formatting
Anton ShumikhinbyAnton Shumikhin·Jan 25, 2025
TLDR
const date1 = new Date('2023-01-01'); const date2 = new Date('2023-01-31'); const diffDays = (date2 - date1) / (1000 * 60 * 60 * 24); console.log(diffDays); // Outputs: 30

Use the JavaScript Date objects to calculate difference in days. Subtract date1 from date2 and divide the result by the number of milliseconds in a day for an exact calculation.

Adjusting for time zones and DST

Account for variations in local time zones and daylight saving time (DST) changes by using UTC dates. Don't be a time traveler, stick with the universal standard:

const date1 = new Date(Date.UTC(2023, 0, 1)); // January 1, 2023 const date2 = new Date(Date.UTC(2023, 0, 31)); // January 31, 2023 const diffDaysUTC = (date2 - date1) / (1000 * 60 * 60 * 24); console.log(diffDaysUTC); // Outputs: 30. It's another day at the office, as expected.

Leap years? We got 'em covered!

To embrace the "leap" in leap years, needless to change your calculation logic. The Date.UTC function handles leap years for you, because it knows that february comes with a twist every four years:

Convert your calculations into reusable functions

While copy-pasting your code is a perennial favorite, a reusable function is a much cleaner, efficient, and consistent solution without the commitment issues:

function daysBetween(startDate, endDate) { // Who are you kidding with non-date inputs? Try again with real Date objects! if (!(startDate instanceof Date) || !(endDate instanceof Date)) { throw new Error('Please provide valid Date objects.'); } // Calculate days difference in UTC. 'Cause who doesn't love standardization? const diffTime = Math.abs(Date.UTC(endDate.getFullYear(), endDate.getMonth(), endDate.getDate()) - Date.UTC(startDate.getFullYear(), startDate.getMonth(), startDate.getDate())); const diffDays = Math.round(diffTime / (1000 * 60 * 60 * 24)); return diffDays; } // Example usage: const startDate = new Date('2023-01-01'); const endDate = new Date('2023-01-31'); console.log(daysBetween(startDate, endDate)); // Outputs: 30. Time flies, doesn't it?

Pro-tip: Your 'daysBetween' function is now a days-calculator-ninja that handles leap years, returns rounded off results, and doesn't forget to stay positive.

Handling those pesky edge cases

Edge cases are like the in-laws of your code - you can't really ignore them:

  • Same date input
  • Non-existent date formats
  • Back-to-the-future inputs (i.e., endDate before startDate)

A golden rule of code etiquette is "handle your edge cases graciously". Throw clear error messages and direct your inputs like a Netflix drama.