更新时间:2023-02-06 16:43:21
当分钟<时,你错过了连接字符串10
和秒< 10
所以你没有得到理想的结果。
You missed concatenating the string when minutes < 10
and seconds < 10
so you were not getting the desired result.
使用 Number()$ c将字符串转换为数字$ c>并正确使用它,如下面的工作代码段所示:
Convert string to number using Number()
and use it appropriately as shown in the working code snippet below:
编辑:更新后的代码 Number()
声明小时
,分钟
和秒
。
Updated code to use Number()
while declaration of hours
, minutes
and seconds
.
var time = "16:30:00"; // your input
time = time.split(':'); // convert to array
// fetch
var hours = Number(time[0]);
var minutes = Number(time[1]);
var seconds = Number(time[2]);
// calculate
var timeValue;
if (hours > 0 && hours <= 12) {
timeValue= "" + hours;
} else if (hours > 12) {
timeValue= "" + (hours - 12);
} else if (hours == 0) {
timeValue= "12";
}
timeValue += (minutes < 10) ? ":0" + minutes : ":" + minutes; // get minutes
timeValue += (seconds < 10) ? ":0" + seconds : ":" + seconds; // get seconds
timeValue += (hours >= 12) ? " P.M." : " A.M."; // get AM/PM
// show
alert(timeValue);
console.log(timeValue);
阅读: Number()
| MDN
Read up: Number()
| MDN