2015-12-15 118 views
0

我是nodeJs的新手,在我的項目中使用了moment.js。我想計算幾分鐘和幾秒鐘的日期時間差異。我GOOGLE了,但沒有得到相關的解決方案。以小時分鐘和秒爲單位的日期時間差異節點js中的moment.js

這是我的代碼和我在谷歌的努力。

var moment = require('moment'); 

var now = "26/02/2014 10:31:30"; 
var then = "25/02/2014 10:20:30"; 

var config = "DD/MM/YYYY HH:mm:ss"; 

var duration = moment.utc(moment(now, config).diff(moment(then,config))).format("HH:mm:ss"); 

console.log(duration); 

這將打印00:11:00 預期的結果是23:11:00

任何幫助,將不勝感激和感謝提前。

+0

我遇到的問題是,對於'now'和'then'格式不正確,以momentjs的最新版本的格式。 我相信你正試圖向後計算(從現在到過去)。 但是,這一刻將返回'then'和'now'之間的時間差 - 這相當於'24:11:00' –

回答

0

你將不得不補充:

var d = moment.duration(ms); 
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss"); 

輸出:24:11:00

由於您的時間差大於24小時,它被重置爲零。從那裏開始剩餘的11分鐘。因此輸出00:11:00。

var moment = require('moment'); 

var now = "26/02/2014 10:31:30"; 
var then = "25/02/2014 10: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"); 

console.log(s); 
0

正如下面和我的評論鏈接引用,您的格式將零到00:11:00格式24小時以上。

https://stackoverflow.com/a/18624295/2903169

現在我只是檢查這一點,並提供從下面這個答案的一個片段。

var moment = require('moment'); 

var now = "26/02/2014 10:31:30"; 
var then = "25/02/2014 10:20:30"; 

var config = "DD/MM/YYYY HH:mm:ss"; 
var ms = moment(now, config).diff(moment(then,config)); 
var d = moment.duration(ms); 
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss"); 

console.log(s) // will log "24:11:00" 

道具Matt Johnson提供答案

+0

謝謝馬特約翰遜多數民衆贊成在我工作 – user3446467

+0

你應該接受答案作爲解決方案,並關閉問題 – user3452275

相關問題