Home > Web Front-end > JS Tutorial > How to Calculate the Time Difference Between Two Datetime Strings?

How to Calculate the Time Difference Between Two Datetime Strings?

Susan Sarandon
Release: 2024-11-20 12:28:15
Original
292 people have browsed it

How to Calculate the Time Difference Between Two Datetime Strings?

Time Difference Calculation

Problem: Determine the time difference between two provided datetime strings.

Example:

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

// Expected output: "00:39:30"
Copy after login

Solution:

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

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

Using a Moment.js plugin:

Moment-Duration-Format

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

The above is the detailed content of How to Calculate the Time Difference Between Two Datetime Strings?. 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