JavaScript date difference

In this article, we will see how to calculate the difference between two dates by using JavaScript. If we use the right methods, then the technique of calculating the difference is straightforward.

The date object is required to calculate the difference between the dates in JavaScript. The JavaScript date object can be used to get a year, month and day. The difference between the dates can be calculated in no. of days, years, or also in the number of milliseconds.

Now we see some illustrations of calculating the difference between two dates in days, years or milliseconds.

In the first example, we will see how to calculate the difference between two dates in no. of days using JavaScript.

Example1

This is an example of getting the difference in no. of days between the specified two dates. In this example, we are applying an approach to calculate the difference.

Here, first, we are defining two dates by using the new date(), then we calculate the time difference between both specified dates by using the inbuilt getTime(). Then we calculate the number of days by dividing the difference of time of both dates by the no. of milliseconds in a day that are (1000*60*60*24).

Here the variable d1 stores the first date, and variable d2 stores the second date. The variable diff stores the difference between the time, and the variable daydiff stores the difference between the dates.

Test it Now

Output

JavaScript date difference

Example2

It is an example of calculating the difference between two dates in a number of years. This example calculates the number of years passed since "10/02/1869" to the present day.

Here the variable d1 stores the first date, and variable d2 stores the present date. The variable diff stores the difference between the time of both dates, and the variable daydiff stores the difference between the dates. Using this approach, we can also find the age of a person.

Test it Now

Output

JavaScript date difference




Contact US

Email:[email protected]

JavaScript date difference
10/30