Skip to content

Instantly share code, notes, and snippets.

@apolopena
Last active May 2, 2023 12:24
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save apolopena/ad4af8bb58e2b1f18b1e0bb78143ebdc to your computer and use it in GitHub Desktop.
Save apolopena/ad4af8bb58e2b1f18b1e0bb78143ebdc to your computer and use it in GitHub Desktop.
JavaScript: convert 12 hours time string to 24 hour time string
// NOTE: time string must look like this 07:05:45PM or this 07:05:45AM and account for 12:00:00AM and convert 12:00:00pm to 12:00:00
function timeConversion(s) {
const ampm = s.slice(-2);
const hours = Number(s.slice(0, 2));
let time = s.slice(0, -2);
if (ampm === 'AM') {
if (hours === 12) { // 12am edge-case
return time.replace(s.slice(0, 2), '00');
}
return time;
} else if (ampm === 'PM') {
if (hours !== 12) {
return time.replace(s.slice(0, 2), String(hours + 12));
}
return time; // 12pm edge-case
}
return 'Error: AM/PM format is not valid';
}
// less lines using array.split/join and modulus (not my solution)
function timeConversionSlicker(s) {
let AMPM = s.slice(-2);
let timeArr = s.slice(0, -2).split(":");
if (AMPM === "AM" && timeArr[0] === "12") {
// catching edge-case of 12AM
timeArr[0] = "00";
} else if (AMPM === "PM") {
// everything with PM can just be mod'd and added with 12 - the max will be 23
timeArr[0] = (timeArr[0] % 12) + 12
}
return timeArr.join(":");
}
@compumatter
Copy link

Thank you. Slicker works perfectly.

@AgentPrus
Copy link

Cool thanks. Works like a charm!

@AnalyzePlatypus
Copy link

Excellent, thanks!

@ComradeLV
Copy link

Missing input parameter in second function

@apolopena
Copy link
Author

@ComradeLV thanks, I updated it.

@MohdAliyan27
Copy link

const time = '12:10 AM';

function convertTo24HrsFormat(time) {
// write your solution here
let [hours, min] = time.split(":");
let [minutes, mode] = min.split(" ");
if(time.endsWith("AM")){
if (hours == 12) {
hours = 12-hours;
hours="0"+hours;
//console.log(hours)
}else if (hours < 10) {
hours="0"+hours;
//console.log(hours)
}
else{
//console.log(hours)
}
if (minutes < 10) {
minutes=parseInt(minutes)
minutes="0"+minutes;
//console.log(minutes)
}else{
//console.log(minutes)
}
//sMinutes = "0" + sMinutes;
} else if(time.endsWith("PM")){
if(hours<12){
hours = parseInt(hours)+12
//console.log(hours)
}
if (minutes < 10) {
minutes = parseInt(minutes)
minutes="0"+minutes;
//console.log(minutes)
}else{
//console.log(minutes)
}
}
return ${hours}:${minutes};
}

console.log(Converted time: ${convertTo24HrsFormat(time)})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment