将毫秒转换为ISO 8601持续时间

3
什么是使用Moment.js将毫秒时间持续时间转换为ISO 8601持续时间的最简单方法?
例如:
3600000 milliseconds > PT1H
2个回答

4

由于这是搜索如何使用JavaScript将毫秒转换为ISO 8601持续时间时的热门结果之一,因此对于那些无法或不想使用Moment.js的人,这是一种使用原始JS的方法。

const duration = (ms) => {
  const dt = new Date(ms);
  const units = [
    ['Y', dt.getUTCFullYear() - 1970],
    ['M', dt.getUTCMonth()],
    ['D', dt.getUTCDate() - 1],
    ['T', null],
    ['H', dt.getUTCHours()],
    ['M', dt.getUTCMinutes()],
    ['S', dt.getUTCSeconds()]
  ];
  
  let str = units.reduce((acc, [k, v]) => {
    if (v) {
      acc += v + k;
    } else if (k === 'T') {
      acc += k;
    } 
    return acc;
  }, '');
  
  str = str.endsWith('T') ? str.slice(0, -1) : str;
  return str ? `P${str}` : null;
};

console.log(duration(110723405000));
// P3Y6M4DT12H30M5S
console.log(duration(3600000));
// PT1H


这不涉及到小数秒。我已经修改了elems中的最后一个元素,以便于我的使用情况:['S', ${dt.getUTCSeconds()}.${dt.getUTCMilliseconds()}] - sarumont

1
你可以这样做:

// Duration 1 hour
var duration = moment.duration(1, 'h');
console.log( duration.asMilliseconds() )   // 3600000

// Convert to ISO8601 duration string
console.log( duration.toISOString() )      // "PT1H"

同时,5分钟就像:

var duration = moment.duration(5, 'm');
console.log( duration.asMilliseconds() )   // 300000

// Convert to ISO8601 duration string
console.log( duration.toISOString() )      // "PT5M"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接