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

How to Accurately Calculate the Time Difference Between Two Datetimes using moment.js?

DDD
Release: 2024-11-17 11:39:01
Original
299 people have browsed it

How to Accurately Calculate the Time Difference Between Two Datetimes using moment.js?

Get Time Difference Between Datetimes

Determining the time difference between two specific datetimes is a common requirement in many applications. This article provides a comprehensive guide to obtaining a precise time interval using moment.js, addressing potential issues and offering alternative approaches.

Problem Statement

Given two datetimes represented as strings, the goal is to calculate the time difference and display it in an HH:MM:SS format. For instance:

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

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

Initial Attempt and Issue

Using moment.js's diff function, you might try the following:

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, this approach incorrectly adds 10 hours, despite the internal values of the duration being accurate.

Correct Solution

To resolve this issue, there are two options:

Option 1 (for durations less than 24 hours):

moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
Copy after login

This approach converts the time difference to UTC, eliminating any daylight saving time inconsistencies.

Option 2 (for durations of 24 hours or greater):

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

This approach calculates the time difference in milliseconds, converts it to a duration object, and extracts the hours, minutes, and seconds separately.

Alternative Approach: moment-duration-format

For those seeking a convenient solution for formatting duration objects, a third-party plugin called moment-duration-format can be employed:

var s = d.format("hh:mm:ss");
Copy after login

The above is the detailed content of How to Accurately Calculate the Time Difference Between Two Datetimes using moment.js?. 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