Created
March 18, 2022 04:14
-
-
Save neos1803/1c1957e44d8d47e4a65d5ce3a25dbf9b to your computer and use it in GitHub Desktop.
AM/PM to 24-Hour-Based Time Converter Javascript
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
function amPmConversion(time = "") { | |
const arr = time.split(":"); | |
const amPm = arr.slice(2,3).join("").split("").slice(2,4).join(""); | |
let converted = ["", arr[1], arr.slice(2,3).join("").split("").slice(0,2).join("")]; | |
if (amPm === "PM") { | |
if (arr[0] === "12") { | |
converted[0] = "12" | |
} else { | |
converted[0] = (Number(arr[0]) + 12).toString(); | |
} | |
} | |
if (amPm === "AM") { | |
if (arr[0] === "12") { | |
converted[0] = "00" | |
} { | |
converted[0] = arr[0]; | |
} | |
} | |
return converted.join(":"); | |
} | |
// Example in AM | |
const am = "06:40:03AM"; | |
console.log(amPmConversion(am)); // Will return 06:40:03 | |
// Example in PM | |
const pm = "07:05:07PM"; | |
console.log(amPmConversion(pm)); // Will return 19:05:07 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment