如何在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP