我正在使用以下逻辑来
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 = endDate.getTime() - startDate.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`;
}
}
如何使用“时刻”获得相同的输出?
正如 jabaa 所提到的,您应该避免使用 moment.js,因为它现在处于维护状态。
您可以尝试 day.js,它是现代的等效版本,不需要花费大量精力来修改您的代码。
您可以通过yarn/npm安装它,包名称为
dayjs
然后你可以这样写:
const startDate = new Date("2024-03-18")
const endDate = new Date("2024-03-18 17:00");
console.log(calculateDateDifference(startDate, endDate))
const startDate2 = new Date("2024-03-10")
const endDate2 = new Date();
console.log(calculateDateDifference(startDate2, endDate2))
function calculateDateDifference(startDate, endDate) {
const difference = dayjs(endDate).diff(startDate, 'millisecond');
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));
if (days > 1) {
return `${days} Days, ${hours} Hours, ${minutes} Mins`;
} else {
return `${hours} Hours, ${minutes} Mins`;
}
}
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
我很欣赏你提到的 Angular,为了允许在 Stackoverflow 上运行,我只使用了纯 JS 和 HTML,但这也应该适用于 Angular。