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

如何用Moment将倒计时字符串转换为毫秒?代码返回0的问题

解决moment转换倒计时字符串为总毫秒数的问题

你当前代码里的milliseconds()方法只会返回时间对象中的毫秒部分(范围0-999),而不是把时分秒整体转换成总毫秒数,这就是结果为0的原因。

要获取倒计时字符串对应的总等待毫秒数,你可以通过和基准时间(比如moment(0),代表"00:00:00"的时间对象)计算差值的方式实现:

const moment = require("moment")

const countdown = "00:02:32"
// 计算目标时间与基准时间的毫秒差值
const totalWaitMillis = moment(countdown, "hh:mm:ss").diff(moment(0))
console.log(totalWaitMillis) // 输出 152000,对应2分32秒的总毫秒数

也可以通过valueOf()方法直接计算时间戳差值,效果一致:

const moment = require("moment")

const countdown = "00:02:32"
const baseTime = moment(0, "hh:mm:ss")
const targetTime = moment(countdown, "hh:mm:ss")
const totalWaitMillis = targetTime.valueOf() - baseTime.valueOf()
console.log(totalWaitMillis) // 同样输出152000

本质上,moment(countdown, "hh:mm:ss")创建的是包含当前系统日期+指定时分秒的时间对象,我们需要的是这个时分秒对应的时长,因此和起始的0时长基准做差值计算,就能得到对应的总毫秒数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 12:17:06