Home > Web Front-end > JS Tutorial > body text

How to Accurately Calculate the Time Difference Between Two Datetimes in JavaScript?

Patricia Arquette
Release: 2024-11-19 05:41:02
Original
584 people have browsed it

How to Accurately Calculate the Time Difference Between Two Datetimes in JavaScript?

How to Get the Time Difference Between Datetimes

Determining the time difference between two instances is a fundamental task in various programming scenarios. This article delves into how to calculate this difference effectively using specific examples.

Consider the following requirement:

var now  = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";

//expected result:
"00:39:30"
Copy after login

Initially, you might try the following approach:

var now = moment("04/09/2013 15:00:00");
var then = moment("04/09/2013 14:20:30");

console.log(moment(moment.duration(now.diff(then))).format("hh:mm:ss"))
// outputs 10:39:30
Copy after login

However, in this example, the unexpected value "10" appears in the result. This is because moment.duration converts the difference between now and then into an object containing internal values like milliseconds. To convert this duration into a time interval, you can use:

duration.get("hours") + ":" + duration.get("minutes") + ":" + duration.get("seconds")
Copy after login

This would produce the desired result: "00:39:30."

Note: This approach is suitable only for durations less than 24 hours. For larger durations, you need a different approach.

var now  = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";

var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");

// outputs: "48:39:30"
Copy after login

In this case, we calculate the time difference as milliseconds, convert it to a duration object d, and then format it using UTC time. This gives us the correct result, "48:39:30."

Alternatively, you can use the moment-duration-format plugin to simplify the formatting process.

The above is the detailed content of How to Accurately Calculate the Time Difference Between Two Datetimes 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template