lifetracker/packages/shared/utils/hours.ts

40 lines
1.1 KiB
TypeScript

export function getHourFromTime(time: number, includePeriod: 'none' | 'twelves' | 'all' = 'none', displayTZ = "") {
const hour = time == 0 || time == 12 ? 12 : time % 12;
const period = time < 12 ? "AM" : "PM";
switch (includePeriod) {
case 'none':
return `${hour}`;
case 'twelves':
return hour === 12 ? `${hour} ${period}` : `${hour}`;
case 'all':
return `${hour} ${period}`;
default:
throw new Error("Invalid includePeriod option. Use either 'none', 'twelves', or 'all'");
}
}
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 < 0) {
// throw new Error("Invalid hour");
// }
if (period === 'PM' && time !== 12) {
time += 12;
} else if (period === 'AM' && time === 12) {
time = 0;
}
return time;
}