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. .
Sample output:
20:00:00 8:0:0 P.M.
08:00:00 08:0:0 A.M
16:00:00 4:30:0 P.M.
I want to achieve the output which looks like the following:
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
To convert from standard time to military time, simply add 12 to the hour. So, if it's 5:30 p.m. standard time, you can add 12 to get the resulting 1730 in military time. To convert from military time to standard time, just subtract 12 from the hour.
'AM' : 'PM'; // Set AM/PM time[0] = +time[0] % 12 || 12; // Adjust hours } return time. join (''); // return adjusted time or original string } tConvert ('18:00:00'); This function uses a regular expression to validate the time string and to split it into its component parts.
You missed concatenating the string when minutes < 10
and seconds < 10
so you were not getting the desired result.
Convert string to number using Number()
and use it appropriately as shown in the working code snippet below:
EDIT: 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);
Read up: Number()
| MDN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With