将军事时间转换为上午和下午时间的最佳方法是什么. .
我有以下代码,它工作正常:
我有以下代码,它工作正常:
$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.
那里有什么建议吗?谢谢
解决方法
分钟时,你错过了连接字符串. 10秒和<秒10所以你没有得到理想的结果. 使用Number()将字符串转换为数字并正确使用它,如下面的工作代码片段所示: 编辑:更新代码以使用Number(),同时声明小时,分钟和秒.
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);