29 lines
752 B
TypeScript
29 lines
752 B
TypeScript
export function getHourFromTime(time: number, includePeriod = false) {
|
|
const hour = time == 0 || time == 12 ? 12 : time % 12;
|
|
const period = time < 12 ? "AM" : "PM";
|
|
return includePeriod ? `${hour} ${period}` : `${hour}`;
|
|
}
|
|
|
|
export function getTimeFromHour(hour: string) {
|
|
const match = hour.match(/^(\d{1,2}) ?([aApP][mM])?$/);
|
|
if (!match) {
|
|
throw new Error("Invalid time format");
|
|
}
|
|
|
|
let time = parseInt(match[1]);
|
|
const period = match[2] ? match[2].toUpperCase() : null;
|
|
|
|
if (time > 12 || time < 1) {
|
|
throw new Error("Invalid hour");
|
|
}
|
|
|
|
if (period === 'PM' && time !== 12) {
|
|
time += 12;
|
|
} else if (period === 'AM' && time === 12) {
|
|
time = 0;
|
|
}
|
|
|
|
return time;
|
|
}
|
|
|