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.
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));
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.
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)
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!