我有一个持续时间字符串,看起来像:
1:16.352
式中1
为分部,16
为秒部,352
为毫秒部。
我想使用Duration.fromISOTime
,但我得到:
{
"reason": "unparsable",
"explanation": "the input "1:16.352" can't be parsed as ISO 8601"
}
在Luxon中是否有一种清晰的方法来解析这样的持续时间?Duration.fromISOTime
不工作,因为1:16.352
是不是在ISO 8601时间字符串中,小时部分缺失(参见ISO 8601时间)。
创建一个LuxonDuration
对象的方法如下:
const DateTime = luxon.DateTime;
const Duration = luxon.Duration;
const startOfHour = DateTime.local().startOf('hour').toMillis();
const dt = DateTime.fromFormat("1:16.352", "m:ss.SSS"). toMillis();
const dur = Duration.fromMillis(dt - startOfHour);
console.log(dur.toFormat("m 'minute' s 'second' S 'millis'"));
<script src="https://cdn.jsdelivr.net/npm/luxon@1.26.0/build/global/luxon.js"></script>
与@VincenzoC类似,我调整了输入string
:
const Duration = luxon.Duration;
var output;
const durationInput = "1:16.352"
if (durationInput.match(/:/g) || [].length === 1) {
const semicolonLocation = durationInput.indexOf(":");
if (semicolonLocation === 1) {
output = "00:0" + durationInput;
}
if (semicolonLocation === 2) {
output = "00:" + durationInput;
}
}
console.log(Duration.fromISOTime(output));
<script src="https://cdn.jsdelivr.net/npm/luxon@1.26.0/build/global/luxon.js"></script>
正如我在评论中提到的,您可以将fromObject
静态方法与简单地将输入拆分为minutes
、seconds
和milliseconds
配置选项结合使用。在您的情况下,一个简单的正则表达式(d+):(d+).(d+)
就可以完成任务,不需要临时日期或规范化。
const { Duration } = luxon;
const durationInput = "1:16.352";
const fromCustom = (input) => {
const [, minutes, seconds, milliseconds ] = input.match(/(d+):(d+).(d+)/);
return Duration.fromObject({
minutes, seconds, milliseconds
});
};
console.log(fromCustom(durationInput));
<script src="https://cdn.jsdelivr.net/npm/luxon@1.26.0/build/global/luxon.js"></script>