Home > Article > Web Front-end > How to Calculate the Time Difference Between Two Datetime Strings?
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!