Open In App

How to Calculate the Number of Days between Two Dates in JavaScript?

Last Updated : 16 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Calculating the number of days between two dates is a common task in web development, especially when working with schedules, deadlines, or event planning. JavaScript provides a simple and effective way to perform this calculation by using different approaches. Whether you’re comparing past and future dates or tracking time intervals, understanding how to calculate the number of days between two dates can be very helpful.

Approaches to Get the Number of Days Between Two Dates

1. Using the Date Object

  • Create two Date objects representing the start and end dates.
  • Subtract one Date object from the other to get the difference in milliseconds.
  • Convert milliseconds into days by dividing by the number of milliseconds in a day (86400000).

Now, let us understand with the help of the example:

javascript
function calculateDays(startDate, endDate) {
    let start = new Date(startDate);
    let end = new Date(endDate);
    let timeDifference = end - start;
    let daysDifference = timeDifference / (1000 * 3600 * 24);
    return daysDifference;
}

let startDate = '2025-04-01';
let endDate = '2025-04-16';
console.log(calculateDays(startDate, endDate)); // 15

Output
15

2. Using Current date

  • We create two Date objects.
  • One using new Date() to represent the current date.
  • Another with the end date provided.
  • Subtract the current date from the end date to get the time difference in milliseconds.
  • Convert the time difference into days by dividing by 86400000 (the number of milliseconds in a day).
  • Since we want to ensure that any partial day is rounded up to the next whole day, we use Math.ceil() to round up the result.

Now, let us understand with the help of the example:

javascript
function calculateDaysFromToday(endDate) {
    // Create Date object for the current date
    let currentDate = new Date();

    // Create Date object for the end date
    let end = new Date(endDate);

    // Calculate time difference in milliseconds
    let timeDifference = end - currentDate;

    // Convert milliseconds to days and use Math.ceil to avoid fractional days
    let daysDifference = Math.ceil(timeDifference / (1000 * 3600 * 24));

    return daysDifference;
}

// Example usage
let endDate = '2025-04-16';
let daysUntilEndDate = calculateDaysFromToday(endDate);

console.log(`The number of days from today to ${endDate} is: ${daysUntilEndDate}`);

Output
The number of days from today to 2025-04-16 is: 0

3. Using UTC timestamps

  • Convert both the start and end dates into UTC timestamps to avoid issues caused by different time zones.
  • Subtract the UTC timestamp of the start date from the UTC timestamp of the end date to get the time difference in milliseconds.
  • Divide the result by 86400000 (the number of milliseconds in a day) to get the number of days.
  • This method ensures that the calculation is consistent, regardless of local time zone settings.

Now, let us understand with the help of the example:

JavaScript
let date1 = new Date("01/16/2024");
let date2 = new Date("01/26/2024");

// Convert dates to UTC timestamps
let utc1 = 
	Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate());
let utc2 = 
	Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate());

// Calculate the time difference in milliseconds
let timeDiff = Math.abs(utc2 - utc1);

// Convert milliseconds to days
let daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));

// Display the result
console.log(`Total number of days between dates:
${date1.toDateString()} and ${date2.toDateString()} is: ${daysDiff} days`);

Output
Total number of days between dates:
Tue Jan 16 2024 and Fri Jan 26 2024 is: 10 days

4. Using Moment.js Library

  • Add Moment.js to your project by installing it via npm or linking it in your HTML file.
  • Use moment() to create date objects for the start and end dates.
  • Use the .diff() method to find the difference between the two dates in days.
  • The result will be the number of days between the two dates.
  • Moment.js makes it easy to handle date calculations with simple syntax.

Now, let us understand with the help of the example:

JavaScript
let startDate = moment('2025-04-01');  // Start date
let endDate = moment('2025-04-16');    // End date

// Calculate the difference in days
let daysDifference = endDate.diff(startDate, 'days');

// Output the result
console.log(`The number of days between the two dates is: ${daysDifference}`);

Best Practices for Calculating Days Between Dates in JavaScript

  • Use Date Correctly: Ensure proper creation of Date objects using new Date() for current date and specific date strings like new Date(‘2025-04-16’).
  • Handle Time Zones and UTC: For consistent results across different time zones, use Date.UTC() or convert dates to UTC before calculation.
  • Consider Time of Day: Set time to midnight if time of day is not relevant, or round the result using Math.floor() or Math.ceil() to handle partial days.
  • Use Libraries: Use date manipulation libraries like Moment.js or Date-fns for complex date calculations and better accuracy.

Conclusion

Calculating the number of days between two dates in JavaScript is straightforward with the Date object. By understanding how to create date objects, handle time zones, and manage time differences, you can easily calculate the days between dates. If you need more advanced features or want to simplify your code, using libraries like Moment.js can be very helpful.



Next Article

Similar Reads