时差函数给出负值

问题描述 投票:0回答:1

我正在使用以下逻辑来

calculate the time difference

但是,当

days > 1
时,这会给出错误的结果值。 请帮助简化代码。

我将在角度框架中使用时差逻辑。

const startDate = new Date(form.value.startDate);
const endDate = new Date();
const dateDiff = this.calculateDateDifference(startDate, endDate);

calculateDateDifference(startDate, endDate) {
    const difference = startDate.getTime() - endDate.getTime();

    const seconds = Math.floor((difference / 1000) % 60);
    const minutes = Math.floor((difference / (1000 * 60)) % 60);
    const hours = Math.floor((difference / (1000 * 60 * 60)) % 24);
    const days = Math.floor(difference / (1000 * 60 * 60 * 24));

    console.log(days + ' days ' + hours + ' hours ' + minutes + ' minutes ' + seconds + ' seconds');
    if (days > 1) {
        return `${days} Days, ${hours} Hours, ${minutes} Mins`;
    } else {
        return `${hours} Hours, ${minutes} Mins`;
    }
}
javascript node.js angular javascript-objects node-modules
1个回答
0
投票

根据文档

Date 实例的 getTime() 方法返回该日期自纪元以来的毫秒数,纪元定义为 UTC 1970 年 1 月 1 日开始的午夜。

自 1970 年以来,

startDate
的毫秒数应该更少,然后
endDate
,

所以,正确的选项是:

const difference = endDate.getTime() - startDate.getTime();
© www.soinside.com 2019 - 2024. All rights reserved.