Home  >  Article  >  Web Front-end  >  How to calculate minutes between two dates in JavaScript?

How to calculate minutes between two dates in JavaScript?

PHPz
PHPzforward
2023-09-05 14:33:02656browse

如何在 JavaScript 中计算两个日期之间的分钟数?

In this article, you will learn how to calculate the number of minutes between two dates in JavaScript.

Date objects work with dates and times. Date objects are created using new Date(). The JavaScript will use the browser's time zone and display the 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));

illustrate

  • Step 1 - Define two datetime 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 value and dividing it by 1000. Divide the result again by 60 to get the minutes.

  • Step 4 - Display the minute difference as the result.

Example 2

In this example, we can calculate the time difference without using a function.

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)

illustrate

  • Step 1 - Define two datetime values ​​dateTimeValue1 and dateTimeValue2.

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

  • Step 3 - Display the minute difference as the result.

The above is the detailed content of How to calculate minutes between two dates in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete