How to use Two different dates In Javascript

  • 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");

// Calculating the time difference
// of two dates
let Difference_In_Time =
    date2.getTime() - date1.getTime();

// Calculating the no. of days between
// two dates
let Difference_In_Days =
    Math.round
        (Difference_In_Time / (1000 * 3600 * 24));

// To display the final no. of days (result)
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

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 simple arithmetic using milliseconds. Below are the methods commonly used to determine the number of days between two dates:

Table of Content

  • Using Two different dates
  • Using One fixed date
  • Using UTC timestamps
  • Using Intl.DateTimeFormat Method

Similar Reads

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....

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....

Using UTC timestamps

Another method to calculate the number of days between two dates involves converting both dates into UTC timestamps and then finding the difference. This approach can be useful when dealing with dates across different time zones, ensuring consistent results regardless of the local time zone settings....

Using Intl.DateTimeFormat Method

The Intl.DateTimeFormat method can be used to format dates and calculate the difference in days between two dates. This method is particularly useful for handling locale-specific date formatting and calculations....