js获取时间差,返回格式为01天02小时03秒

2023-02-10  本文已影响0人  storyWrite
// 获取时间差 返回值格式:01天02小时30秒
export function caclulateDiffTime(start, end): string {
  start = new Date(start).getTime();
  end = new Date(end).getTime();
  let staytimeGap = end - start;
  if (staytimeGap < 0) {
    staytimeGap = start - end;
  }
if(isNaN(staytimeGap )) {
  throw new Error('时间参数有误!');
}
  // 计算
  let stayDay = Math.floor(staytimeGap / (3600 * 1000 * 24));
  let modHour = staytimeGap % (24 * 1000 * 3600);
  let stayHour = Math.floor(modHour / (3600 * 1000));
  let modMin = modHour % (3600 * 1000);
  let stayMin = Math.floor(modMin / (60 * 1000));
  let modSec = modMin % (60 * 1000);
  let staySec = Math.floor(modSec / 1000);

  const timeArr = [
    {
      title: '天',
      time: stayDay,
    },
    {
      title: '小时',
      time: stayHour,
    },
    {
      title: '分钟',
      time: stayMin,
    },
    {
      title: '秒',
      time: staySec,
    },
  ];
  return timeArr
    .map((item) => {
     // 补0 
      if (item.time < 10) {
        item.time = '0' + item.time;
      }
      return item;
    })
   // 去除时间为0项
    .filter((item) => item.time > 0)
    .map((item) => item.time + item.title)
    .join('');
}
上一篇下一篇

猜你喜欢

热点阅读