共计 692 个字符,预计需要花费 2 分钟才能阅读完成。
js 通过 moment 计算两个时间相差的天数和时分秒,
需求:如果相差超过 1 天,显示相差天数 + 小时 + 分钟,相差不超过 1 天,显示相差小时 + 分钟,不超过 1 小时,显示相差分钟。
**
主要运用 moment 以下方法:
moment().diff(); 获得以毫秒为单位的差异
moment.duration().minutes() 获取分钟数 (0 – 59)。
moment.duration().hours() 获取小时数 (0 – 23)。
moment.duration().days() 获得天数 (0 – 30)。
**
function timeDifference(time1, time2) {
const duration = moment.duration(moment(time2).diff(moment(time1)));
let result = '';
if (duration.days() > 0) {
result += `${duration.days()}d`;
}
if (duration.hours() > 0) {
if (result) {
result += `/`;
}
result += `${duration.hours()}h`;
}
if (duration.minutes() > 0) {
if (result) {
result += `/`;
}
result += `${duration.minutes()}min`;
}
return result || '1min';
}
console.log(timeDifference(new Date('2023-12-20 16:01:20'),new Date()));
原文地址: js 通过 moment 计算两个时间相差的天数和时分秒
正文完