How to calculate minutes between two dates in JavaScript?


In this article, you will understand how to calculate minutes between two dates in JavaScript.

The Date object works with dates and times. Date objects are created with new Date(). JavaScript will use the browser's time zone and display a date as a full text string.

Example 1

In this example, we use a function to find the time difference.

function minutesDiff(dateTimeValue2, dateTimeValue1) {
   var differenceValue =(dateTimeValue2.getTime() - dateTimeValue1.getTime()) / 1000;
   differenceValue /= 60;
   return Math.abs(Math.round(differenceValue));
}

dateTimeValue1 = new Date(2020,12,12);
console.log("The first date time value is defined as: ", dateTimeValue1)

dateTimeValue2 = new Date(2020,12,13);
console.log("The second date time value is defined as: ", dateTimeValue2)

console.log("
The difference in the two date time values in minutes is: ") console.log(minutesDiff(dateTimeValue1, dateTimeValue2));

Explanation

  • Step 1 − Define two date time values dateTimeValue1 and dateTimeValue2.

  • Step 2 − Define a function minutesDiff that takes two date values as parameters.

  • Step 3 − In the function, calculate the time difference by subtracting the date values and dividing it by 1000. Divide the result again by 60 to get the minutes.

  • Step 4 − Display the minutes difference as the result.

Example 2

In this example, we compute the time difference without functions.

dateTimeValue1 = new Date(2020,12,12);
console.log("The first date time value is defined as: ", dateTimeValue1)

dateTimeValue2 = new Date(2020,12,13);
console.log("The second date time value is defined as: ", dateTimeValue2)

console.log("
The difference in the two date time values in minutes is: ") var differenceValue =(dateTimeValue2.getTime() - dateTimeValue1.getTime()) / 1000; differenceValue /= 60; let result = Math.abs(Math.round(differenceValue)) console.log(result)

Explanation

  • Step 1 −Define two date time values dateTimeValue1 and dateTimeValue2.

  • Step 2 −Calculate the time difference by subtracting the date values and dividing it by 1000. Divide the result again by 60 to get the minutes.

  • Step 3 −Display the minutes difference as the result.

Updated on: 16-Feb-2023

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements