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

How Can Moment.js Be Used to Calculate and Format Time Differences in JavaScript?

Patricia Arquette
Release: 2024-11-18 07:02:02
Original
150 people have browsed it

How Can Moment.js Be Used to Calculate and Format Time Differences in JavaScript?

Get the Difference between Time Differences

In programming, it's often necessary to calculate the difference between two dates or times. Moment.js is a popular JavaScript library that simplifies working with dates and times. In this article, we'll explore how to use Moment.js to get the time difference between two timestamps.

Using Moment.js for Time Differences

To start, we can create two Moment.js objects for our example timestamps:

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

Using the diff() method, we can get the difference between now and then:

var ms = now.diff(then);
Copy after login

The result of ms is a Moment.js Duration object, which represents the time difference in milliseconds. To format the duration as a readable string, we can use:

var result = moment.utc(ms).format("HH:mm:ss");
Copy after login

This gives us the expected result: "00:39:30".

Handling Durations over 24 Hours

If the duration exceeds 24 hours, the above approach will reset the hours to zero. To handle this, we can manually extract the hours and separately format the minutes and seconds:

var d = moment.duration(ms);
var hours = Math.floor(d.asHours());
var mins = d.minutes();
var secs = d.seconds();

var result = hours + ":" + mins + ":" + secs; // e.g. "48:39:30"
Copy after login

Alternatively, you can use a third-party plugin like moment-duration-format for more convenient formatting options.

The above is the detailed content of How Can Moment.js Be Used to Calculate and Format Time Differences 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