Last active
July 5, 2024 08:05
-
-
Save apolopena/ad4af8bb58e2b1f18b1e0bb78143ebdc to your computer and use it in GitHub Desktop.
JavaScript: convert 12 hours time string to 24 hour time string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(":"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)}
)