更正 JavaScript 中的時間字串
問題
我們要求編寫一個 JavaScript 函式,該函式以“HH:MM:SS”格式的時間字串作為輸入。
但是增加了一個問題,因此許多時間字串是損壞的,這意味著 MM 部分可能超過 60,SS 部分也可能超過 60。
我們的函式應對字串進行必要的更改,並返回新的更正字串。
例如 −
"08:11:71" -> "08:12:11"
示例
以下為程式碼 −
const str = '08:11:71';
const rectifyTime = (str = '') => {
if(!Boolean(str)){
return str;
};
const re = /^(\d\d):(\d\d):(\d\d)$/;
if (!re.test(str)){
return null;
};
let [h, m, s] = str.match(re).slice(1,4).map(Number);
let time = h * 3600 + m * 60 + s;
s = time % 60;
m = (time / 60 |0) % 60;
h = (time / 3600 |0) % 24;
return [h, m, s]
.map(String)
.join(':');
};
console.log(rectifyTime(str));輸出
以下為控制檯輸出 −
08:12:11
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP