Best way to convert military time to standard time in javascript

As Nit recommend, 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>

As an extension to Huy Hoang Pham's answer, here's the code with Luxon rather than moment.js (see this and this)

import { DateTime }  from "luxon";

function convert(input) {
    return DateTime.fromFormat(input, 'HH:mm:ss').toFormat('h:mm:ss A');
}

console.log(convert('20:00:00'));
console.log(convert('08:00:00'));
console.log(convert('16:30:00'));

Time is complicated, and I would recommend using a library over your own code for conversions like this.


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

Tags:

Javascript