Files
portfolio/src/shared/lib/utils/formatDate/formatDate.ts
T

39 lines
1.0 KiB
TypeScript
Raw Normal View History

const MONTH_FMT = new Intl.DateTimeFormat('en-US', { month: 'short', year: 'numeric', timeZone: 'UTC' });
function formatMonthYear(date: Date): string {
return MONTH_FMT.format(date);
}
/**
* Formats a PocketBase date string into a localized month+year range or "Present".
* @throws {Error} if any date is invalid or if the range is logically impossible.
*/
export function formatMonthYearRange(start: string, end: string | null): string {
const startDate = new Date(start);
if (Number.isNaN(startDate.getTime())) {
throw new Error('Invalid start date');
}
if (end === null) {
return `${formatMonthYear(startDate)} — Present`;
}
const endDate = new Date(end);
if (Number.isNaN(endDate.getTime())) {
throw new Error('Invalid end date');
}
if (startDate > endDate) {
throw new Error('Start date cannot be after end date');
}
const startLabel = formatMonthYear(startDate);
const endLabel = formatMonthYear(endDate);
if (startLabel === endLabel) {
return startLabel;
}
return `${startLabel}${endLabel}`;
}