Determine Time Difference in JavaScript
Calculating the time difference between two text-boxes in JavaScript can be accomplished through the following approach:
Step 1: Convert Strings to Date Objects
Begin by creating two Date objects from the text-box strings. Specify an arbitrary date part, the input time, and set the timezone to UTC.
let time1 = "09:00"; let time2 = "17:00"; let date1 = new Date(`2000-01-01T${time1}Z`); let date2 = new Date(`2000-01-01T${time2}Z`);
Step 2: Adjust for Times Crossing Midnight
In some scenarios, the times may span midnight. To handle this, check if the second date is earlier than the first. If so, add a day to the second date.
if (date2 < date1) { date2.setDate(date2.getDate() + 1); }
Step 3: Calculate the Difference
Subtract the first date object from the second to obtain the difference in milliseconds.
let diff = date2 - date1;
Step 4: Format the Result
Depending on the display requirements, you can format the result as needed.
For example, to display the difference as a time string:
let hours = Math.floor(diff / (1000 * 60 * 60)); let minutes = Math.floor((diff / (1000 * 60)) % 60); let result = `${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}`;
The above is the detailed content of How to Calculate the Time Difference Between Two Times in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!