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

在JavaScript中如何将'3w2d24h'时间字符串转换为毫秒?

时间字符串转毫秒的实现方案

方案1:使用moment.js实现

如果你的项目已经在使用moment.js,可以通过正则拆分时间片段配合moment的duration能力实现转换:

  • 实现代码:
const moment = require('moment');

const timeStrToMs = (timeStr) => {
  // 匹配数字+时间单位的片段,支持w(周)、d(天)、h(小时)、m(分钟)、s(秒)
  const timeReg = /(\d+)([wdhms])/g;
  let totalMs = 0;
  let matchResult;
  while ((matchResult = timeReg.exec(timeStr)) !== null) {
    const [, num, unit] = matchResult;
    totalMs += moment.duration(Number(num), unit).asMilliseconds();
  }
  return totalMs;
}

// 测试用例
console.log(timeStrToMs('3w2d24h')); 

说明:moment.duration默认单位定义和需求匹配:1w=7天、1d=24小时、1h=3600秒。

方案2:使用轻量专用库parse-duration实现

如果不想自己写正则拆分,或者项目没有引入moment.js,可以使用专门做时间字符串解析的parse-duration库,代码更简洁:

  • 安装命令:npm install parse-duration
  • 实现代码:
const parseDuration = require('parse-duration');

const ms = parseDuration('3w2d24h');
console.log(ms); // 直接返回转换后的毫秒数值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:15:09