在 Luxon 中像持续时间一样解析 ISO 8601

Parsing ISO 8601 like duration in Luxon

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

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 does not work since 1:16.352 is not an ISO 8601 time string, the hour part is missing (see ISO 8601 Times).

构建 Luxon Duration 对象的解决方法如下:

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 静态方法结合简单地将输入拆分为 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>