Get time difference between datetimes Ask Question

Get time difference between datetimes Ask Question

How to get the difference between 2 times? Example:

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

//expected result:
"00:39:30"

I tried:

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

What is "10" there? I am at utc-0300. Result of moment.duration(now.diff(then)) is a duration with correct internal values:

 days: 0
 hours: 0
 milliseconds: 0
 minutes: 39
 months: 0
 seconds: 30
 years: 0

How to convert a momentjs duration to a time interval? I can use:

duration.get("hours") +":"+ duration.get("minutes") +:+ duration.get("seconds")

But is there something more elegant? now is:

Tue Apr 09 2013 15:00:00 GMT-0300 (E. South America Standard Time)…}

そしてmoment(moment.duration(now.diff(then)))

Wed Dec 31 1969 22:39:30 GMT-0200 (E. South America Daylight Time)…}

1969 年 12 月 31 日には夏時間が使用されたため、値は -0200 になります。

ベストアンサー1

このアプローチは、合計期間が 24 時間未満の場合にのみ機能します。

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

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

// outputs: "00:39:30"

24 時間以上ある場合、上記の方法では時間がゼロにリセットされるため、理想的ではありません。

24 時間以上の有効な応答を取得したい場合は、代わりに次のようにする必要があります。

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

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

// outputs: "48:39:30"

d.minutes()UTC 時間をショートカットとして使用していることに注意してください。と を別々に取り出すこともできますd.seconds()が、ゼロパディングも必要になります。

durationこれが必要なのは、現在 moment.js に異議をフォーマットする機能がないためです。これは、ここでリクエストされています。ただし、この目的専用のmoment-duration-formatというサードパーティのプラグインがあります。

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

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 = d.format("hh:mm:ss");

// outputs: "48:39:30"

おすすめ記事