PThhHmmMssS 日期格式转换为时间

问题描述 投票:0回答:1

我需要将此格式“PThhHmmMssS”(PT7H45M26.75S)转换为时间戳。有没有办法使用 moment.js 来做到这一点

我在论坛中寻找解决方案,但一无所获。我不明白这种格式基于什么标准。如果你能帮我解开这个谜团那就太好了。

javascript timestamp
1个回答
0
投票

格式“PThhHmmMssS”是 ISO 8601 持续时间格式之一,这是表示日期、时间和持续时间的国际标准。

  • “P”表示持续时间的开始。
  • “T”将日期部分(如果存在)与时间部分分开。
  • “hh”代表小时。
  • “mm”代表分钟。
  • “ss”代表秒。
  • “S”代表毫秒。

“PT”表示这是一个持续时间。 “7H”代表7小时。 “45M”代表45分钟。 “26.75S”代表26.75秒,所以你有7小时45分钟26.75秒。

你不需要时间。只是一个正则表达式和一些日期操作

const parseAndAddDurationToCurrentDate = (durationString) => {
  const regex = /P(?:T(\d+)H)?(\d+)M([\d.]+)S/;
  const match = durationString.match(regex);

  if (!match) {
    throw new Error('Invalid duration format');
  }

  const hours = match[1] ? parseInt(match[1]) : 0;
  const minutes = parseInt(match[2]);
  const seconds = parseFloat(match[3]);

  const currentDate = new Date();
  currentDate.setHours(currentDate.getHours() + hours);
  currentDate.setMinutes(currentDate.getMinutes() + minutes);
  currentDate.setSeconds(currentDate.getSeconds() + seconds);

  return currentDate;
};

// Example usage:
const durationString = "PT7H45M26.75S";
const newDate = parseAndAddDurationToCurrentDate(durationString);

console.log("New Date:", newDate);

© www.soinside.com 2019 - 2024. All rights reserved.