如何在 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
廣告