我在全球范围内遇到两次截然不同的问题。我需要比较时间格式天:小时:分钟:秒。一切正常,但hour中出现问题。在此示例中,小时应为0小时,但返回6小时。。
function getTimeDiff(join, lastSeen) {
let t1 = new Date(join).getTime(),
t2 = new Date(lastSeen).getTime(),
milliseconds = 0,
time = '';
if (isNaN(t1) || isNaN(t2)) return '';
if (t1 < t2) {milliseconds = t2 - t1;}
else {milliseconds = t1 - t2;}
var days = Math.floor(milliseconds / 1000 / 60 / (60 * 24));
var date_diff = new Date(milliseconds);
if (days > 0) time += days + 'd ';
console.log('join: ', join, ' - ', 'lastseen:', lastSeen);
console.log('Diff = ', milliseconds);
console.log('Standard Time : ', date_diff);
console.log('Hours: ', date_diff.getHours());
console.log('Minutes: ', date_diff.getMinutes());
console.log('Secounds: ', date_diff.getSeconds());
if (date_diff.getHours() > 0) time += date_diff.getHours() + 'h ';
if (date_diff.getMinutes() > 0) time += date_diff.getMinutes() + 'm ';
if (date_diff.getSeconds() > 0) time += date_diff.getSeconds() + 's ';
console.log('Result: ', time);
return time;
}
console.log(getTimeDiff(1589911275699, 1589911365116));
输出结果:
**
1589911275699 " -- " 1589911365116
join: 1589911275699 - lastseen: 1589911365116
Diff = 89417
Standard Time : Thu Jan 01 1970 06:01:29 GMT+0600 (Bangladesh Standard Time)
Hours: 6 // Result should be 0
Minutes: 1
Secounds: 29
Result: 6h 1m 29s // 0h 1m 29s
**
当您构造日期对象(new Date(milliseconds)
)时,它会在您的时区中创建日期对象(我认为您的格林威治标准时间为+6),因此您可以获得+6小时的时间。