如何使用 moment.js 解析 ISO 8601 格式的持续时间?

How do I parse an ISO 8601 formatted duration using moment.js?

我有一个 ISO 8601 格式的持续时间,例如:PT5M 或 PT120S。

有什么方法可以使用 moment.js 解析这些并获取持续时间中指定的分钟数?

谢谢!

PS:我看了Parse ISO 8601 durationsConvert ISO 8601 time format into normal time duration

但很想知道这是否可行。

它似乎不是受支持的格式之一:http://momentjs.com/docs/#/durations/

不乏使用正则表达式解决问题的 github 回购协议(如您所见,基于您提供的链接)。这在不使用日期的情况下解决了它。还需要一点时间吗?

var regex = /P((([0-9]*\.?[0-9]*)Y)?(([0-9]*\.?[0-9]*)M)?(([0-9]*\.?[0-9]*)W)?(([0-9]*\.?[0-9]*)D)?)?(T(([0-9]*\.?[0-9]*)H)?(([0-9]*\.?[0-9]*)M)?(([0-9]*\.?[0-9]*)S)?)?/

minutesFromIsoDuration = function(duration) {
    var matches = duration.match(regex);

    return parseFloat(matches[14]) || 0;
}

如果你测试它:

minutesFromIsoDuration("PT120S");

0

minutesFromIsoDuration("PT5M");

5

如果你想要以分钟为单位的逻辑持续时间,你可能会逃避:

return moment.duration({
    years: parseFloat(matches[3]),
    months: parseFloat(matches[5]),
    weeks: parseFloat(matches[7]),
    days: parseFloat(matches[9]),
    hours: parseFloat(matches[12]),
    minutes: parseFloat(matches[14]),
    seconds: parseFloat(matches[16])
});

接着是

result.as("minutes");

时刻 parse ISO-formatted durations 使用 moment.duration 方法开箱即用:

moment.duration('P1Y2M3DT4H5M6S')

regex is gnarly, but supports a number of edge cases and is pretty thoroughly tested.

如果 moment.js 对于您的用例来说太重了:我已经打包了一个小包来帮助完成此操作:

import { parse, serialize } from 'tinyduration';
 
// Basic parsing
const durationObj = parse('P1Y2M3DT4H5M6S');
assert(durationObj, {
    years: 1,
    months: 2,
    days: 3,
    hours: 4,
    minutes: 5,
    seconds: 6
});
 
// Serialization
assert(serialize(durationObj), 'P1Y2M3DT4H5M6S');
Install using npm install --save tinyduration or yarn add tinyduration

参见:https://www.npmjs.com/package/tinyduration