Member-only story
JavaScript Interview Prep: Convert time to military (24-hour) time
1 min readJun 21, 2024
Prompt
Given a time in -hour AM/PM format, convert it to military (24-hour) time.
Sample Input
07:05:45PM
Sample Output
19:05:45
Solution
'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', function(inputStdin) {
inputString += inputStdin;
});
process.stdin.on('end', function() {
inputString = inputString.split('\n');
main();
});
function readLine() {
return inputString[currentLine++];
}
/*
* Complete the 'timeConversion' function below.
*
* The function is expected to return a STRING.
* The function accepts STRING s as parameter.
*/
function timeConversion(s) {
const isAM = s.includes("AM");
const removeAMPM = s.replace("AM", "").replace("PM","");
const splitColumn = removeAMPM.split(":");
const hour = splitColumn[0]
let timeWithoutHour = "";
splitColumn.forEach((each, eachIndex) => {
if (eachIndex == 0){
} else {
timeWithoutHour = timeWithoutHour + ":" + each;
}
});
let output = "";
if (isAM){
if (hour.length == 1){
output = "0"+removeAMPM;
} else if (hour == "12"){
output = "00"+timeWithoutHour;
} else {
output = removeAMPM;
}
}
if…