如何在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
热门推荐
10 新年祝福语简短的个性
11 兔年祝福语简短100字
12 高考已上岸祝福语简短
13 学生祝福语简短古诗句
14 简短创意祝福语有什么
15 租房明天搬家祝福语简短
16 老公生日祝福语简短好看
17 团体年会祝福语简短霸气
18 送师姐的祝福语简短