如何在 JavaScript 中将"HH:MM:SS"格式转换为秒数

javascriptweb developmentobject oriented programming更新于 2025/9/29 21:32:17

我们需要编写一个函数,该函数接受"HH:MM:SS"字符串并返回秒数。例如 −

countSeconds(‘12:00:00’) //43200
countSeconds(‘00:30:10’) //1810

让我们为此编写代码。我们将拆分字符串,将字符串数组转换为数字数组并返回适当的秒数。

此代码的完整内容如下 −

示例

const timeString = '23:54:43';
const other = '12:30:00';
const withoutSeconds = '10:30';
const countSeconds = (str) => {
   const [hh = '0', mm = '0', ss = '0'] = (str || '0:0:0').split(':');
   const hour = parseInt(hh, 10) || 0;
   const minute = parseInt(mm, 10) || 0;
   const second = parseInt(ss, 10) || 0;
   return (hour*3600) + (minute*60) + (second);
};
console.log(countSeconds(timeString));
console.log(countSeconds(other));
console.log(countSeconds(withoutSeconds));

输出

控制台中的输出将是 −

86083
45000
37800

相关文章


有用资源