Yes, you can use moment.js to do this - but I'm not sure if it's strictly necessary as it can also be accomplished through simple string manipulation.
(是的,您可以使用moment.js来执行此操作-但我不确定它是否严格必要,因为它也可以通过简单的字符串操作来实现。)
String Manipulation Approach:
(字符串处理方法:)
function parseTimeSpan(timeString) {
let parts = timeString.split("h");
return {
hours: Number(parts[0]),
minutes: Number(parts[1].slice(0, -1))
};
}
JsFiddle Here
(JsFiddle在这里)
Note this will only work with strings that contain both the hour and minute component, and does not support seconds.
(请注意,这仅适用于同时包含小时和分钟部分且不支持秒的字符串。)
Moment.JS Approach:
(Moment.JS方法:)
function parseTimeSpan(timeString) {
return moment.duration("PT" + timeString.toUpperCase());
}
JsFiddle Here
(JsFiddle在这里)
This approach is more robust and handles far more use cases, but is slower and requires an external library.
(这种方法更健壮,可处理更多用例,但速度较慢,需要外部库。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…