You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中解析HH:mm:ss,SS自定义时间串转秒数的方法

自定义时间格式转秒数方案

问题背景

当前使用的自定义时间格式示例:02:56:12,80,需要实现该格式字符串到对应秒数的转换。
已实现秒数转该自定义格式的代码如下:

const formatTimeFromSeconds = (seconds) => {
  dateObj = new Date(seconds * 1000);
  hours = dateObj.getUTCHours();
  minutes = dateObj.getUTCMinutes();
  seconds = dateObj.getSeconds();
  milliseconds = dateObj.getMilliseconds();

  timeString =
    hours.toString().padStart(2, "0") +
    ":" +
    minutes.toString().padStart(2, "0") +
    ":" +
    seconds.toString().padStart(2, "0") +
    "," +
    milliseconds.toString().padStart(2, "0");

  return timeString;
};

此前尝试的手动拆分方案存在逻辑错误,代码如下:

const dateToSeconds = (time) => {
  try {
    const times = time.split(":")
    const secondDelimit = times[2].split(".")
    const secondsConversion = parseInt(secondDelimit[0])
    const hoursToSeconds = parseInt(times[0]) * 60 * 60
    const minutesToSeconds = parseInt(times[1]) * 60 

    const totalSeconds = minutesToSeconds + hoursToSeconds + secondsConversion
    return `${totalSeconds}.${secondDelimit[1]}`
  } catch (err) {
    console.error(err)
  }
}

问题点说明

原有代码存在三个核心问题:

  • 分隔符匹配错误:自定义格式中秒和毫秒之间是逗号,不是点,调用split(".")无法拆分出毫秒字段
  • 格式化逻辑存在时区隐患:小时、分钟取的是UTC时区值,秒、毫秒取的是本地时区值,跨时区场景下转换结果会出现偏差
  • 变量未声明:格式化代码中所有变量未加const/let声明,严格模式下会直接报错

可直接使用的解析方案

用正则做格式校验和字段提取,避免多层split的冗余逻辑,同时和原有格式化逻辑完全对齐:

const parseTimeToSeconds = (timeStr) => {
  // 正则匹配HH:MM:SS,xx格式,捕获时、分、秒、两位毫秒四个分组
  const regMatch = timeStr.match(/^(\d{1,2}):(\d{2}):(\d{2}),(\d{1,2})$/);
  if (!regMatch) throw new Error("时间格式不合法,需符合HH:MM:SS,xx规则");

  const [, hours, minutes, seconds, msPart] = regMatch;
  // 统一转成毫秒计算,避免浮点数误差
  const totalMilliseconds = Number(hours) * 3600 * 1000
    + Number(minutes) * 60 * 1000
    + Number(seconds) * 1000
    + Number(msPart.padEnd(3, "0")); // 两位毫秒补0转成标准三位毫秒值

  return totalMilliseconds / 1000;
};

配套修正后的格式化代码

修复原有时区、变量声明问题,和解析逻辑完全双向对齐:

const formatTimeFromSeconds = (totalSeconds) => {
  const dateObj = new Date(totalSeconds * 1000);
  // 全部使用UTC方法,避免时区偏差
  const hours = dateObj.getUTCHours();
  const minutes = dateObj.getUTCMinutes();
  const seconds = dateObj.getUTCSeconds();
  const milliseconds = dateObj.getUTCMilliseconds();

  return [
    hours.toString().padStart(2, "0"),
    minutes.toString().padStart(2, "0"),
    seconds.toString().padStart(2, "0")
  ].join(":") + "," + milliseconds.toString().padStart(3, "0").slice(0, 2);
};

测试验证

传入时间字符串"02:56:12,80",解析结果为2*3600 + 56*60 + 12 + 0.8 = 10572.8秒,将该秒数传入格式化函数,可输出原字符串,双向转换无偏差。

内容的提问来源于stack exchange,提问作者user38643

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 05:42:13