1

我的持续时间字符串如下所示:

1:16.352

其中1是分钟部分,16是秒部分,352是毫秒部分。

我想使用Duration.fromISOTime,但我得到:

{
  "reason": "unparsable",
  "explanation": "the input \"1:16.352\" can't be parsed as ISO 8601"
}

在 Luxon 中是否有一种干净的方式来解析这种持续时间?

4

3 回答 3

3

Duration.fromISOTime不起作用,因为1:16.352不是ISO 8601 时间字符串,缺少小时部分(请参阅 I SO 8601 Times)。

构建 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>

于 2021-02-18T14:08:13.950 回答
2

与@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>

于 2021-02-18T16:23:11.243 回答
1

正如我在评论中提到的,您可以fromObject结合使用静态方法,只需将输入拆分为minutessecondsmilliseconds配置选项。在您的情况下,一个简单的正则表达式(\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>

于 2021-02-19T02:21:34.527 回答