How to Calculate the Number of Days between Two Dates in JavaScript?
Last Updated :
16 Apr, 2025
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
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}`);
OutputThe 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`);
OutputTotal 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.
Similar Reads
Convert a negative number to positive in JavaScript In this article, we will see how we can convert a negative number to a positive number in JavaScript by the methods described below. Below are the methods to convert a negative number to a positive in JavaScript: Table of Content Multiplying by -1Using Math.abs()adding a minus signFlipping the bitUs
4 min read
Check a Number is Prime or Not Using JavaScript A prime number is a whole number greater than 1, which has no positive divisors other than 1 and itself. In other words, prime numbers cannot be formed by multiplying two smaller natural numbers. For example:2, 3, 5, 7, 11, and 13 are prime numbers.4, 6, 8, 9, and 12 are not prime numbers because th
5 min read
JavaScript - Convert a Number into JS Array You have a number, like 12345, and you need to convert it into an array where each element represents a digit of the number. For example, 12345 should become [1, 2, 3, 4, 5]. How can you achieve this in JavaScript?In JavaScript, there are various ways to transform a number into an array of its digit
3 min read
How to generate a n-digit number using JavaScript? The task is to generate an n-Digit random number with the help of JavaScript. You can also generate random numbers in the given range using JavaScript. Below are the approaches to generate a n-digit number using JavaScript: Table of Content Using Math.random()Math.random() Method and .substring() Me
2 min read
How to get decimal portion of a number using JavaScript ? Given a float number, The task is to separate the number into integer and decimal parts using JavaScript. For example, a value of 15.6 would be split into two numbers, i.e. 15 and 0.6 Here are a few methods discussed. These are the following methods: Table of Content Javascript String split() Method
3 min read
Generate Random Number in Given Range Using JavaScript Here are the different ways to generate random numbers in a given range using JavaScript1. Using Math.random(): basic ApproachThis is the simplest way to generate a random number within a range using Math.random().JavaScriptlet min = 10; let max = 20; let random = Math.floor(Math.random() * (max - m
3 min read
How to convert long number into abbreviated string in JavaScript ? We are given a long number and the task is to convert it to the abbreviated string(eg.. 1234 to 1.2k). Here 2 approaches are discussed with the help of JavaScript.Approaches to Convert Long Number to Abbreviated String:Table of ContentUsing JavaScript methodsUsing Custom functionUsing logarithmsUsin
6 min read
How to check first number is divisible by second one in JavaScript ? Given two numbers and the task is to check the first number is divisible by the second number or not with the help of JavaScript. Before getting into the coding part, first let us know about the modulo operator and triple equals. To find a number is divisible by another or not, we simply use the rem
2 min read
JavaScript - How to Get a Number of Vowels in a String? Here are the various methods to get the number of vowels in a string using JavaScript.1. Using a for LoopThis is the most basic and beginner-friendly approach. It uses a loop to iterate over each character and checks if it is a vowel.JavaScriptconst cVowels = (s) => { const vowels = "aeiouAEIOU";
3 min read
How to limit a number between a min/max value in JavaScript ? We can limit a number between a min/max value using the is-else condition and using the Math.min and Math.max methods of JavaScript.Below are the approaches to limit a number between a min/max value in JavaScript:Table of ContentUsing the if-else conditionUsing the Math.min() and Math.max() methodsU
2 min read