Best way to convert wartime to standard time in javascript

What is the best way to convert wartime to am and pm. 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) ? " PM" : " AM"; //console.log( timeValue); } 

But I am not satisfied with the output when I run my program.,

Output Example:

 20:00:00 8:0:0 PM 08:00:00 08:0:0 AM 16:00:00 4:30:0 PM 

I want to get a result that looks like this:

 20:00:00 8:00:00 PM 08:00:00 8:00:00 AM 16:30:00 4:30:00 PM 

Are there any suggestions? Thanks

+6
source share
2 answers

You skipped string concatenation at minutes < 10 and seconds < 10 so as not to get the desired result.

Convert the string to a number using Number() and use it appropriately, as shown in the working code snippet below:

EDIT: Updated code to use Number() when declaring 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) ? " PM" : " AM"; // get AM/PM // show alert(timeValue); console.log(timeValue); 

Reading: Number() | MDN

+7
source

As Nit recommends, Moment.js provides a simple solution to your problem.

 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> 
+3
source

Source: https://habr.com/ru/post/984120/


All Articles