Nodejs中的时间差异?

我试图找出一种方法来获得两个date之间的时间差秒。

例如,秒之间的差异:

2013-5-11 8:37:18 2013-5-11 10:37:18 

尝试:

 function timeDifference(laterdate, earlierdate) { var difference = laterdate.getTime() - earlierdate.getTime(); var daysDifference = Math.floor(difference/1000/60/60/24); difference -= daysDifference*1000*60*60*24 var hoursDifference = Math.floor(difference/1000/60/60); difference -= hoursDifference*1000*60*60 var minutesDifference = Math.floor(difference/1000/60); difference -= minutesDifference*1000*60 var secondsDifference = Math.floor(difference/1000); return secondsDifference; } 

但是这在Nodejs中不起作用,与错误

的getTime()

function没有被发现

       

网上收集的解决方案 "Nodejs中的时间差异?"

 var moment = require('moment') var startDate = moment('2013-5-11 8:73:18', 'YYYY-M-DD HH:mm:ss') var endDate = moment('2013-5-11 10:73:18', 'YYYY-M-DD HH:mm:ss') var secondsDiff = endDate.diff(startDate, 'seconds') console.log(secondsDiff) 

你将需要moment.js模块

 npm install -S moment 

时区完成模块支持date差异,即使date在不同的时区。 它返回一个单元感知的Duration对象,而不仅仅是一个表示“毫秒”的“数字”:

 var tc = require("timezonecomplete"); var start = new tc.DateTime("2014-06-26T12:00:00 Europe/Amsterdam"); var end = new tc.DateTime("2014-06-26T12:00:00 UTC"); var duration = end.diff(start); // unit-aware duration console.log(duration.minutes()); // -120 console.log(duration.hours()); // -2 

获取剩余的日子:

 var moment = require('moment'); var startDate = moment(new Date()).format("YYYY-MM-DD"); var endDate = moment(new Date("Tue Aug 27 2015 09:13:40 GMT+0530 (IST)")).format("YYYY-MM-DD"); var remainingDate = moment(endDate).diff(startDate, 'days'); console.log(remainingDate) // at time of posting, 106 days