Home > Web Front-end > JS Tutorial > How to Calculate the Time Difference Between Two Times in JavaScript?

How to Calculate the Time Difference Between Two Times in JavaScript?

DDD
Release: 2024-11-21 18:20:15
Original
618 people have browsed it

How to Calculate the Time Difference Between Two Times in JavaScript?

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`);
Copy after login

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);
}
Copy after login

Step 3: Calculate the Difference

Subtract the first date object from the second to obtain the difference in milliseconds.

let diff = date2 - date1;
Copy after login

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}`;
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template