将军事时间转换为上午和下午时间的最佳方法是什么。 . 我有以下代码并且工作正常:
$scope.convertTimeAMPM = function(time){
//var time = "12:23:39";
var time = time.split(':');
var hours = time[0];
var minutes = time[1];
var seconds = time[2];
$scope.timeValue = "" + ((hours >12) ? hours -12 :hours);
$scope.timeValue += (minutes < 10) ? ":0" : ":" + minutes;
$scope.timeValue += (seconds < 10) ? ":0" : ":" + seconds;
$scope.timeValue += (hours >= 12) ? " P.M." : " A.M.";
//console.log( timeValue);
}
但是我对运行程序时的输出显示不满意。 .
示例输出:
20:00:00 8:0:0 P.M.
08:00:00 08:0:0 A.M
16:00:00 4:30:0 P.M.
我想实现如下所示的输出:
20:00:00 8:00:00 P.M.
08:00:00 8:00:00 A.M
16:30:00 4:30:00 P.M.
有什么建议吗?谢谢
最佳答案
当 minutes < 10
时,您错过了连接字符串和 seconds < 10
所以你没有得到想要的结果。
使用 Number()
将字符串转换为数字并适本地使用它,如下面的工作代码片段所示:
编辑:更新代码以使用 Number()
同时声明 hours
, minutes
和 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
关于javascript - 在javascript中将军事时间转换为标准时间的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29206453/