Files
sorsfonalak/services/frontend/src/lib/birth.ts
T

52 lines
1.6 KiB
TypeScript
Raw Normal View History

// Our own date and time fields for birth data (not the browser's date and
// time inputs: those follow the operating system's or the browser's region,
// with US order and AM/PM in Safari).
export const MONTHS = [
"január",
"február",
"március",
"április",
"május",
"június",
"július",
"augusztus",
"szeptember",
"október",
"november",
"december",
];
const pad = (n: number) => String(n).padStart(2, "0");
export const daysIn = (year: number, month: number) => new Date(Date.UTC(year || 2000, month, 0)).getUTCDate();
/** "YYYY-MM-DD" from the three fields, or null while it is not a real date. */
export function composeDate(year: string, month: string, day: string): string | null {
const y = Number(year);
const m = Number(month);
const d = Number(day);
if (!/^\d{4}$/.test(year) || y < 1000 || !m || !d || d > daysIn(y, m)) return null;
return `${year}-${pad(m)}-${pad(d)}`;
}
/** "HH:MM" from the two fields, or null while it is not a real time. */
export function composeTime(hour: string, minute: string): string | null {
if (!/^\d{1,2}$/.test(hour) || !/^\d{1,2}$/.test(minute)) return null;
const h = Number(hour);
const m = Number(minute);
return h <= 23 && m <= 59 ? `${pad(h)}:${pad(m)}` : null;
}
/** Birth data typed into the public chart page (sessionStorage), offered on the profile after sign-up in the same tab. */
export const BIRTH_DRAFT_KEY = "sf_birth_draft";
export interface BirthDraft {
date: string;
time: string | null;
country: string;
geonames_id: number;
placeName: string;
region: string | null;
}