javascript 如何使用 moment.js 解析 ISO 8601 格式的持续时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27851832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I parse an ISO 8601 formatted duration using moment.js?
提问by Qrious
I have an ISO 8601 formatted duration, for eg: PT5M or PT120S.
我有一个 ISO 8601 格式的持续时间,例如:PT5M 或 PT120S。
Is there any way I can parse these using moment.js and fetch the number of minutes specified in the duration?
有什么办法可以使用moment.js解析这些并获取持续时间中指定的分钟数吗?
Thank you!
谢谢!
PS: I looked at Parse ISO 8601 durationsand Convert ISO 8601 time format into normal time duration
PS:我查看了Parse ISO 8601 durationsand Convert ISO 8601 time format into normal time duration
but was keen to know if this was do-able with moment.
但很想知道这是否可行。
回答by bollwyvl
moment doesparse ISO-formatted durationsout of the box with the moment.duration
method:
moment确实使用以下方法解析 ISO 格式的持续时间moment.duration
:
moment.duration('P1Y2M3DT4H5M6S')
The regex is gnarly, but supports a number of edge cases and is pretty thoroughly tested.
回答by Mark Dickson Jr.
It doesn't appear to be one of the supported formats: http://momentjs.com/docs/#/durations/
它似乎不是支持的格式之一:http: //momentjs.com/docs/#/durations/
There aren't any shortage of github repos that solve it with regex (as you saw, based on the links you provided). This solves it without using Date. Is there even a need for moment?
使用正则表达式解决它的 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;
}
If you test it:
如果你测试它:
minutesFromIsoDuration("PT120S");
minutesFromIsoDuration("PT120S");
0
0
minutesFromIsoDuration("PT5M");
minutesFromIsoDuration("PT5M");
5
5
If you want the logical duration in minutes, you might get away with:
如果您想要以分钟为单位的逻辑持续时间,您可能会逃脱:
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])
});
followed by
其次是
result.as("minutes");