在javascript中将军事时间转换为标准时间的最佳方法

新手上路,请多包涵

将军事时间转换为上午和下午时间的最佳方法是什么。 .我有以下代码并且工作正常:

 $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.

那里有什么建议吗?谢谢

原文由 Lee Lee 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 241
2 个回答

您错过了在 minutes < 10seconds < 10 时连接字符串,因此您没有得到想要的结果。

使用 Number() 将字符串转换为数字,并适当地使用它,如下面的工作代码片段所示:

编辑: 更新 seconds 代码要使用 Number() 声明为 hours minutes

 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

原文由 Rahul Desai 发布,翻译遵循 CC BY-SA 4.0 许可协议

正如 Nit 推荐的那样,Moment.js 为您的问题提供了一个简单的解决方案。

 function convert(input) {
    return moment(input, 'HH:mm:ss').format('h:mm:ss A');
}

console.log(convert('20:00:00'));
console.log(convert('08:00:00'));
console.log(convert('16:30:00'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.js"></script>

原文由 Huy Hoang Pham 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题