How to calculate the number of days between two dates in JavaScript ?
To Calculate the number of days between two dates in JavaScript we use the Date
object and perform some basic arithmetic with milliseconds. The below methods can be used to find out the number of days between two dates.
Using Two different dates
- Use new Date() to create two date objects, date1 and date2.
- Use date2.getTime() – date1.getTime() to calculate the time difference in milliseconds between the two dates.
- Divide the time difference by the number of milliseconds in a day (1000 * 60 * 60 * 24) to obtain the number of days.
Example: The following JavaScript program will illustrate the process of finding the number of days between two dates.
javascript
let date1 = new Date( "01/16/2024" );
let date2 = new Date( "01/26/2024" );
let Difference_In_Time =
date2.getTime() - date1.getTime();
let Difference_In_Days =
Math.round
(Difference_In_Time / (1000 * 3600 * 24));
console.log
( "Total number of days between dates:\n" +
date1.toDateString() + " and " +
date2.toDateString() +
" is: " + Difference_In_Days + " days" );
|
Output
Total number of days between dates:
Tue Jan 16 2024 and Fri Jan 26 2024 is: 10 days
Using One fixed date
- Present date is obtained using new Date().
- Christmas date is set using date.getFullYear().
- If Christmas has passed, adjust the date to the next year.
- Calculate the difference in days using Math.round((christmas_day.getTime() – present_date.getTime()) / one_day).
- Log the result to the console with present and Christmas dates.
Example: The below code find out the number of days between the current date and the christmas date.
javascript
let one_day = 1000 * 60 * 60 * 24;
let present_date = new Date();
let christmas_day =
new Date(present_date.getFullYear(), 11, 25);
if (present_date.getMonth() ==
11 && present_date.getDate() > 25) {
christmas_day.setFullYear(christmas_day.getFullYear() + 1);
}
let Result = Math.round((christmas_day.getTime() -
present_date.getTime()) / one_day);
let Final_Result = Result.toFixed(0);
console.log( "Number of days remaining till Christmas:\n" +
present_date.toDateString() + " and " +
christmas_day.toDateString() +
" is: " + Final_Result + " days" );
|
Output
Number of days remaining till Christmas:
Wed Jan 17 2024 and Wed Dec 25 2024 is: 343 days
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Last Updated :
17 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...