Skip to content

Instantly share code, notes, and snippets.

@AlvisonHunterArnuero
Created November 16, 2024 14:52
Show Gist options
  • Save AlvisonHunterArnuero/74695d0e81b4878c5dcd060bf0d8f97d to your computer and use it in GitHub Desktop.
Save AlvisonHunterArnuero/74695d0e81b4878c5dcd060bf0d8f97d to your computer and use it in GitHub Desktop.
/* Converts a time string between 12-hour and 24-hour formats.
* Made with ❤️ with TypeScript by Alvison Hunter - November 16th, 2024.
*
* @param {string} hour - The time string to convert.
* For 12-hour format, use "hh:mm:ss AM/PM".
* For 24-hour format, use "HH:mm:ss".
* @param {boolean} isMilitaryFormat - If `true`, converts from 12-hour to 24-hour format.
* If `false`, converts from 24-hour to 12-hour format.
* @returns {string} - The converted time string.
* For 24-hour format, returns "HH:mm:ss".
* For 12-hour format, returns "hh:mm:ss AM/PM".
*/
const convertTimeFormat = (hour: string, isMilitaryFormat: boolean): string => {
if (isMilitaryFormat) {
// Convert 12-hour format to 24-hour format
const [time, meridian] = hour.split(/(AM|PM)/i);
let [h, m, s] = time.trim().split(":").map(Number);
if (meridian === "PM" && h !== 12) h += 12;
if (meridian === "AM" && h === 12) h = 0;
return `${String(h).padStart(2, "0")}:${String(m || 0).padStart(2, "0")}:${String(s || 0).padStart(2, "0")}`;
} else {
// Convert 24-hour format to 12-hour format
let [h, m, s] = hour.split(":").map(Number);
const meridian = h >= 12 ? "PM" : "AM";
h = h % 12 || 12; // Convert 0 to 12 for 12-hour format
return `${h}:${String(m || 0).padStart(2, "0")}:${String(s || 0).padStart(2, "0")} ${meridian}`;
}
}
// Example usage:
console.log(convertTimeFormat("02:30:16 PM", true)); // "14:30:16"
console.log(convertTimeFormat("14:30", false)); // "2:30:00 PM"
console.log(convertTimeFormat("17:40", false)); // "5:40:00 PM"
console.log(convertTimeFormat("03:16:22", true)); // "03:16:22"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment