我试图找出一种方法来获得两个日期之间的时间差。
例如,之间的差异为:
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()
找不到功能
答案 0 :(得分:31)
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
答案 1 :(得分:4)
timezonecomplete模块支持日期差异,即使是不同时区的日期也是如此。它返回一个可识别单位的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
答案 2 :(得分:1)
获取剩余的日子:
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
答案 3 :(得分:1)
如果只想像我一样在循环上设置超时,则根本不需要使用momentjs。请尝试以下操作。
let timeout = 3; //seconds
console.log("start:" + new Date());
let start = Number(Date.now());
let end = start + timeout * 1000;
while (Number(Date.now()) < end) {
// your code here
}
console.log("end:" + new Date());
PS:我知道这篇文章并不能完全回答所提出的问题,但这是当您搜索“ nodejs的时差”时弹出的链接。
答案 4 :(得分:0)
我们也可以使用这个优化的代码,
function calculateDays(startDate,endDate)
{
var start_date = moment(startDate, 'YYYY-MM-DD HH:mm:ss');
var end_date = moment(endDate, 'YYYY-MM-DD HH:mm:ss');
var duration = moment.duration(end_date.diff(start_date));
var days = duration.asDays();
return days;
}
此处您需要安装moment
并希望在使用之前导入。
答案 5 :(得分:0)
它将检查系统时间并找到差异。
Could not find a version that satisfies the requirement ml-metadata<0.14,>=0.13.2 (from tfx==0.13.0) (from versions: 0.12.0.dev0, 0.13.0.dev0, 0.13.1.dev0) No matching distribution found for ml-metadata<0.14,>=0.13.2 (from tfx==0.13.0)
答案 6 :(得分:0)
const MOMENT = require('moment');
const TimeDiff = ( startTime, endTime, format ) => {
startTime = MOMENT( startTime, 'YYYY-MM-DD HH:mm:ss' );
endTime = MOMENT( endTime, 'YYYY-MM-DD HH:mm:ss' );
return endTime.diff( startTime, format);
}
let startTime = new Date('2013-5-11 8:37:18');
let endTime = new Date('2013-5-11 10:37:18');
console.log( TimeDiff(startTime, endTime, 'seconds'));