Users fill out a form where they enter what date and time an issue started and when it entered and the form will provide the difference between those times in minutes.
So for example if they enter 4/26/2025 10:00 AM for the start time and 4/26/2025 11:00 AM for the end time, the result of the difference between the two times in minutes would be 60.
This is what I have for the fields the users fill out
HTML
<input type="datetime-local" class="datetime" id="StartDateTime" max="2099-12-31T23:59">
<input type="datetime-local" class="datetime" id="EndDateTime" max="2099-12-31T23:59">
This is what I have for my JavaScript:
function calculateMinutesBetweenDates(date1, date2) {
const timeDifferenceMs = Math.abs(date2.getTime() - date1.getTime());
const minutesDifference = Math.floor(timeDifferenceMs / (1000 * 60));
return minutesDifference;
}
const dateString1 = document.getElementById("StartDateTime").value;
const dateString2 = document.getElementById("EndDateTime").value;
const date1 = new Date(dateString1);
const date2 = new Date(dateString2);
const minutes = calculateMinutesBetweenDates(date1, date2);
console.log(`Minutes between dates: ${minutes}`); // Output: Minutes between dates
However the only result I get is NaN instead of 60 as in the example. It's not giving any other JavaScript errors so not sure why it won't calculate the values as the user sets the date and time fields.
If I set the values directly such as:
const startTime = "2025-04-26T10:00:00";
const endTime = "2025-04-26T11:30:00";
Then it works correctly but need the values to change by user input of the HTML fields.
When your first run your html page, the date fields are empty, so the .value
's are empty strings, which yields invalid dates and a NaN
difference calculation.
You need to move the code into a function, and call the function after both date and time fields are fully filled out.
In this code snippet I call the new function with the click of a button.
function calculateMinutesBetweenDates(date1, date2) {
const timeDifferenceMs = Math.abs(date2.getTime() - date1.getTime());
const minutesDifference = Math.floor(timeDifferenceMs / (1000 * 60));
return minutesDifference;
}
function calculate(event) {
const dateString1 = document.getElementById("StartDateTime").value;
const dateString2 = document.getElementById("EndDateTime").value;
const date1 = new Date(dateString1);
const date2 = new Date(dateString2);
const minutes = calculateMinutesBetweenDates(date1, date2);
if( !dateString1 ) console.log( "Please fill out date and time on left side" )
else if( !dateString2 ) console.log( "Please fill out date and time on right side" )
else console.log(`Minutes between dates: ${minutes}`); // Output: Minutes between dates
}
<input type="datetime-local" class="datetime" id="StartDateTime" max="2099-12-31T23:59">
<input type="datetime-local" class="datetime" id="EndDateTime" max="2099-12-31T23:59">
<br>
<button type="button" onclick="calculate(event)">Calculate</button>