Skip to content

Instantly share code, notes, and snippets.

@jrobinsonc
Created November 29, 2023 03:06
Show Gist options
  • Save jrobinsonc/ffab0905d0fab68d0e589bcd06778796 to your computer and use it in GitHub Desktop.
Save jrobinsonc/ffab0905d0fab68d0e589bcd06778796 to your computer and use it in GitHub Desktop.
/**
* @param time - The time in 24 hours format
* @returns The time in 12 hours format
*/
export function convertTime24to12(time: string): string {
const [hours, minutes]: number[] = time.split(':').map(Number);
const meridiem: 'PM' | 'AM' = hours >= 12 ? 'PM' : 'AM';
return `${hours % 12 || 12}:${minutes
.toString()
.padStart(2, '0')} ${meridiem}`;
}
/**
*
* @param time - The time in 12 hours format
* @returns The time in 24 hours format
*/
export function convertTime12to24(time: string): string {
let [hours, minutes]: number[] = time.split(' ')[0].split(':').map(Number);
const meridiem: string = time.split(' ')[1];
if (meridiem.toUpperCase() === 'PM' && hours < 12) hours += 12;
else if (meridiem.toUpperCase() === 'AM' && hours === 12) hours = 0;
return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(
2,
'0',
)}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment