码迷,mamicode.com
首页 > 其他好文 > 详细

formatDuration - 返回毫秒数的可读格式

时间:2018-01-18 17:58:38      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:复数   style   var   day   body   filter   return   ble   label   

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

用适当的值来划分ms,以获得 dayhourminutesecond 和 millisecond 的适当值。 通过 Array.filter() 使用 Object.entries() 只保留非零值。 使用 Array.map() 为每个值创建字符串,并且适当复数化。 使用 String.join(‘, ‘) 将这些值组合成一个字符串。

const formatDuration = ms => {
  if (ms < 0) ms = -ms;
  const time = {
    day: Math.floor(ms / 86400000),
    hour: Math.floor(ms / 3600000) % 24,
    minute: Math.floor(ms / 60000) % 60,
    second: Math.floor(ms / 1000) % 60,
    millisecond: Math.floor(ms) % 1000
  };
  return Object.entries(time)
    .filter(val => val[1] !== 0)
    .map(val => val[1] + ‘ ‘ + (val[1] !== 1 ? val[0] + ‘s‘ : val[0]))
    .join(‘, ‘);
};

formatDuration(1001); // ‘1 second, 1 millisecond‘
formatDuration(34325055574); // ‘397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds‘

formatDuration - 返回毫秒数的可读格式

标签:复数   style   var   day   body   filter   return   ble   label   

原文地址:https://www.cnblogs.com/bali123/p/8311467.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!