Created
November 29, 2023 03:06
-
-
Save jrobinsonc/ffab0905d0fab68d0e589bcd06778796 to your computer and use it in GitHub Desktop.
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
/** | |
* @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