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

如何将含毫秒的时间字符串四舍五入至秒并去除毫秒部分?

如何将带毫秒的时间字符串四舍五入到整秒?

这问题挺常见的,我来给你捋个简单的实现思路~核心逻辑是先把时间转成总秒数做四舍五入,再转回HH:MM:SS格式,具体实现如下:

实现步骤与代码

我写了一个通用函数来处理这个需求,直接复用就行:

function roundTimeToSecond(timeStr) {
  // 1. 拆分时间的时、分、秒(含毫秒)部分
  const [hours, minutes, secWithMs] = timeStr.split(':');
  
  // 2. 计算总秒数(把时分转成秒,加上带小数的秒数)
  const totalSeconds = parseInt(hours) * 3600 + parseInt(minutes) * 60 + parseFloat(secWithMs);
  
  // 3. 对总秒数做四舍五入
  const roundedTotal = Math.round(totalSeconds);
  
  // 4. 把四舍五入后的总秒数转回HH:MM:SS格式,补零确保两位数字
  const h = Math.floor(roundedTotal / 3600).toString().padStart(2, '0');
  const m = Math.floor((roundedTotal % 3600) / 60).toString().padStart(2, '0');
  const s = (roundedTotal % 60).toString().padStart(2, '0');
  
  return `${h}:${m}:${s}`;
}

// 测试你的变量
var x = '00:00:24.320';
var y = '00:00:19.968';

x = roundTimeToSecond(x); // 结果: '00:00:24'
y = roundTimeToSecond(y); // 结果: '00:00:20'

console.log(x, y);

关键细节说明

  • 拆分与转换:用split(':')把时间拆成时、分、秒(含毫秒),再用parseInt和parseFloat转成数字计算总秒数;
  • 四舍五入:Math.round()正好匹配你的需求——24.32秒向下取整为24,19.968秒向上取整为20;
  • 补零处理:padStart(2, '0')确保小时、分钟、秒都是两位数字,避免出现0:0:24这种不规范格式。

这个函数适用于固定格式的HH:MM:SS.sss时间字符串,如果你的时间格式有变化,只需要调整拆分逻辑即可~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:55:57