snippetjavascriptTip
How to calculate date difference in JavaScript
Viewed 0 times
javascriptdatehowcalculatedifference
Problem
Working with dates is hard, but often necessary, which is the reason why there are so many date-related libraries out there. However, some tasks, such as calculating the difference between two dates, can be easily accomplished with vanilla JavaScript.
> [!NOTE]
>
> You may not be familiar with JavaScript's numeric separators, which are used in the examples below. They're syntactic sugar that make large numeric values more readable.
Calculating the date difference in seconds is as simple as subtracting the two
> [!NOTE]
>
> You may not be familiar with JavaScript's numeric separators, which are used in the examples below. They're syntactic sugar that make large numeric values more readable.
Calculating the date difference in seconds is as simple as subtracting the two
Date objects and dividing by the number of milliseconds in a second (1000).Solution
const dateDifferenceInSeconds = (dateInitial, dateFinal) =>
(dateFinal - dateInitial) / 1_000;
dateDifferenceInSeconds(
new Date('2020-12-24 00:00:15'),
new Date('2020-12-24 00:00:17')
); // 2>
> You may not be familiar with JavaScript's numeric separators, which are used in the examples below. They're syntactic sugar that make large numeric values more readable.
Calculating the date difference in seconds is as simple as subtracting the two
Date objects and dividing by the number of milliseconds in a second (1000).Similarly, to calculate the date difference in minutes, we only need to change the divisor to the number of milliseconds in a minute (
1000 * 60).To calculate the date difference in hours, we do the same thing, but with the number of milliseconds in an hour (
1000 60 60).Subtraction can take us further still, calculating the date difference in days. Without taking timezones into account, we can simply divide the difference in milliseconds by the number of milliseconds in a day (
1000 60 60 * 24).Code Snippets
const dateDifferenceInSeconds = (dateInitial, dateFinal) =>
(dateFinal - dateInitial) / 1_000;
dateDifferenceInSeconds(
new Date('2020-12-24 00:00:15'),
new Date('2020-12-24 00:00:17')
); // 2const dateDifferenceInMinutes = (dateInitial, dateFinal) =>
(dateFinal - dateInitial) / 60_000;
dateDifferenceInMinutes(
new Date('2021-04-24 01:00:15'),
new Date('2021-04-24 02:00:15')
); // 60const dateDifferenceInHours = (dateInitial, dateFinal) =>
(dateFinal - dateInitial) / 3_600_000;
dateDifferenceInHours(
new Date('2021-04-24 10:25:00'),
new Date('2021-04-25 10:25:00')
); // 24Context
From 30-seconds-of-code: date-difference
Revisions (0)
No revisions yet.