我有两个UTC格式的日期,即 2019年1月5日星期六12:58:53 GMT 和 2019年1月5日星期六13:07:54 GMT 。我需要找到两个日期之间的时差。到目前为止,我已经尝试了以下代码
function timeDifference(date1, date2) {
var difference = date1.getTime() - date2.getTime();
console.log("difference-0--0", difference)
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);
console.log('difference = ' + daysDifference + ' day/s ' + hoursDifference + ' hour/s ' + minutesDifference + ' minute/s ' + secondsDifference + ' second/s ');
}
timeDifference(new Date('Sat, 05 Jan 2019 12:58:53 GMT'), new Date('Sat, 05 Jan 2019 13:07:54 GMT'))
当我通过格林尼治标准时间2019年1月5日星期六12:58:53和格林尼治标准时间2019年1月5日星期六5:07:54时效果很好。
答案 0 :(得分:1)
尝试测试我的解决方案:
function timeDifference(date1, date2) {
let chage = 0;
let difference = Math.abs(date1.setMilliseconds(0) - date2.setMilliseconds(0)) / 1000;
let days = Math.floor(difference / (60 * 60 * 24));
chage = difference % (60 * 60 * 24);
let hours = Math.floor(chage / (60 * 60));
chage = chage % (60 * 60);
let minutes = Math.floor(chage / 60);
let seconds = chage % 60;
console.log("days:", days, "hours:", hours, "minutes:", minutes, "seconds:", seconds)
}
timeDifference(new Date('Sat, 05 Jan 2019 12:58:53 GMT'), new Date('Sat, 05 Jan 2019 13:07:54 GMT'))