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

How to Calculate the Time Difference Between Two Datetime Strings?

Susan Sarandon
Susan SarandonOriginal
2024-11-20 12:28:15203browse

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"

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")

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");

Using a Moment.js plugin:

Moment-Duration-Format

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

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!

Statement:
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