如何在JavaScript中将'HH:MM:SS'格式转换为秒
我们需要编写一个接受“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