将持续时间(例如 3h 23m)转换为 nodejs 中的日期时间?

Convert a Duration(ex. 3h 23m) to datetime in nodejs?

如何使用 NodeJS 将时间作为字符串 2h 25m 15s2h 10m 转换为 datetime 或像 1h => 60 这样的分钟?

我找不到与此完全相同的副本,但我们有很多很多类似的问题,都类似于 Converting a string to a date in JavaScript. Basically, you just need to take a Date and add those values to it. I'd use Date(0) to keep it simple (uses the ECMAScript epoch)。

请注意,我在此处使用了 JavaScript 最近添加的一些内容:

const durs = [
  '2h 25m 15s',
  '25m 15s',
  '15s',
  '2h 25m',
  '2h',
  '25m'
];

function parseDurationAsDate(duration) {
  const hours = parseInt(/(\d*)h/.exec(duration)?.[0] ?? 0, 10);
  const minutes = parseInt(/(\d*)m/.exec(duration)?.[0] ?? 0, 10);
  const seconds = parseInt(/(\d*)s/.exec(duration)?.[0] ?? 0, 10);
  const date = new Date(0); // date portion is irrelevant
  // especially if we use setUTCHours so that toISOString shows no offset
  date.setUTCHours(hours, minutes, seconds);
  return date;
}
for (let dur of durs) {
  console.log(`Duration:`, dur);
  let dt = parseDurationAsDate(dur);
  console.log('  Date:', dt.toISOString());
  console.log('  Time:', dt.toISOString().slice(11, -1));
}

另一种方法是创建一个函数来分割时间,在指定结构中使用正则表达式(ReGex)({number}h {number}m {number}s):

const splitTime = time => time.match(/((?<hours>\d{1,2})(?:h))?\s?((?<minutes>\d{1,2})(?:m))?\s?((?<seconds>\d{1,2})(?:s))?/).groups;

此函数接受并期望 h m s 格式的输入,每个字母前面都有数字,然后为该输入定义了一个正则表达式,只需将表达式搜索一个数字(例如:(表达式 1) (?<hours>\d{1,2})) 后跟一个字母(例如:(表达式 2) (?:h)),但是字母在组内无法匹配(表达式 ?:),我们用“?”使这个表达式可选在捕获组最外层括号的末尾,例如:(expression 1 expression 2)?,最后我们使 space 之间的 \s? 可选(恰好匹配一个 space之间)。

然后我们可以创建一个接受小时、分钟和秒的函数,默认值为 0(零),如下所示:

const timeToSeconds = ({hours = 0, minutes = 0, seconds = 0}) => Number(hours) * 60 * 60 + Number(minutes) * 60 + Number(seconds);

然后与splitTime函数一起使用:

const seconds = timeToSeconds(splitTime('1h 25s'));
console.log(seconds); // 3625

具有附加功能的完整代码:

const splitTime = time => time.match(/((?<hours>\d{1,2})(?:h))?\s?((?<minutes>\d{1,2})(?:m))?\s?((?<seconds>\d{1,2})(?:s))?/).groups;

const timeToHours = ({hours = 0, minutes = 0, seconds = 0}) => Number(hours) + Number(minutes) / 60 + Number(seconds) / 60 * 60;

const timeToMinutes = ({hours = 0, minutes = 0, seconds = 0}) => Number(hours) * 60 * 60 + Number(minutes) + Number(seconds) / 60;

const timeToSeconds = ({hours = 0, minutes = 0, seconds = 0}) => Number(hours) * 60 * 60 + Number(minutes) * 60 + Number(seconds);

const time = "1h 15m 0s";
const timeSplit = splitTime(time);

console.log(timeToHours(timeSplit));
console.log(timeToMinutes(timeSplit));
console.log(timeToSeconds(timeSplit));

// Missing hours and seconds
console.log(timeToSeconds(splitTime("15m")));