Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
58
rated 0 times [  64] [ 6]  / answers: 1 / hits: 29135  / 9 Years ago, mon, march 23, 2015, 12:00:00

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


More From » javascript

 Answers
10

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


[#67346] Thursday, March 19, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nestorjarettg

Total Points: 451
Total Questions: 108
Total Answers: 108

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
;