使用 Moment.js 将持续时间(以毫秒为单位)转换为 ISO 8601 持续时间的最简单方法是什么?
例如:
3600000 milliseconds > PT1H
最佳答案
因为这是目前搜索如何将毫秒转换为 ISO 8601 duration 的最佳结果之一。对于 JavaScript,对于那些不能或不想使用 Moment.js 的人来说,这是一种使用 vanilla 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
关于javascript - 将毫秒转换为 ISO 8601 持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46633152/