js通过moment计算两个时间相差的天数和时分秒

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()));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值