JavaScript:日期格式化——js毫秒数转换成时间

967人浏览   2023-10-23 15:00:24

返回给定毫秒数的可读格式

思路

  • ms除以适当的值,以获得dayhourminute的值;
  • Object.entries() Array.prototype.filter()配合使用以仅保留非零值;
  • 使用Array.prototype.map()为每个值创建字符串,并适当地进行复数化;
  • 使用String.prototype.join(' ')将值组合成字符串。

实现代码

const formatDuration = ( ms ) => {
  if(ms < 0) ms = -ms;

  let time = {
    day: Math.floor(ms / 86400000),
    hour: Math.floor(ms / 3600000) % 24,
    minute: Math.floor(ms / 60000) % 60
  }

  return Object.entries(time)
    .filter(val => val[1] !== 0)
    .map(([key, val])=>{
      if(key === 'day') return `${val}天`
      
      if(key === 'hour') return `${val}时`

      if(key === 'minute') return `${val}分`
    })
    .join(' ');
}

测试代码

let t1 = formatDuration(62341001);
console.log(t1);

let t2 = formatDuration(34325055574);
console.log(t2);


测试结果

17 19
397 6 44



相关推荐