在javascript中将军事时间转换为标准时间的最佳方法 [英] Best way to convert military time to standard time in javascript

查看:81
本文介绍了在javascript中将军事时间转换为标准时间的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the best way to convert military time to am and pm time. . I have the following code and it works fine:

$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);
}

但是当我运行程序时,我对输出节目不满意。 。

But I am not satisfied in the output shows when I run my program. .

样本输出:

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.

那里有什么建议吗?谢谢

Is there any suggestions there? Thanks

推荐答案

分钟<时,你错过了连接字符串10 秒< 10 所以你没有得到理想的结果。

You missed concatenating the string when minutes < 10 and seconds < 10 so you were not getting the desired result.

使用 Number()并正确使用它,如下面的工作代码段所示:

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

这篇关于在javascript中将军事时间转换为标准时间的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆