Skip to content

Instantly share code, notes, and snippets.

@GitKat
Forked from apolopena/JSConvert12to24Time.js
Created March 31, 2022 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GitKat/7f561bce45929452ec198a364895196a to your computer and use it in GitHub Desktop.
Save GitKat/7f561bce45929452ec198a364895196a 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(":");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment