// server/utils/gameDay.ts // Helper to get the start of a given date for daily EXP checks const getStartOfDay = (date: Date) => { const d = new Date(date); d.setUTCHours(0, 0, 0, 0); // Use UTC for calendar day consistency return d; }; export function getTodayDay(): string { const today = getStartOfDay(new Date()); return today.toISOString().split('T')[0]; // Returns "YYYY-MM-DD" } export function isBeforeDay(day1: string | null | undefined, day2: string): boolean { if (!day1) return true; // A null/undefined day is always before any valid day for our logic (e.g., first time processing) return day1 < day2; // Lexicographical comparison works for "YYYY-MM-DD" } export function getPreviousDay(): string { const yesterday = getStartOfDay(new Date()); yesterday.setUTCDate(yesterday.getUTCDate() - 1); return yesterday.toISOString().split('T')[0]; } export function daysSince(pastDay: string, futureDay: string): number { // We work with UTC dates to avoid timezone issues. const pastDate = new Date(`${pastDay}T00:00:00Z`); const futureDate = new Date(`${futureDay}T00:00:00Z`); // getTime() returns milliseconds since epoch const diffTime = futureDate.getTime() - pastDate.getTime(); // 1000 ms/s * 60 s/min * 60 min/hr * 24 hr/day const diffDays = Math.round(diffTime / (1000 * 60 * 60 * 24)); return diffDays > 0 ? diffDays : 0; } /** * Converts a "YYYY-MM-DD" string into the application's day-of-week convention. * @param gameDay A string in "YYYY-MM-DD" format. * @returns A number where Monday is 0 and Sunday is 6. */ export function getDayOfWeekFromGameDay(gameDay: string): number { // Create a date object from the string. Appending 'T00:00:00Z' ensures it's parsed as UTC, // preventing the user's server timezone from shifting the date. const date = new Date(`${gameDay}T00:00:00Z`); const jsDayOfWeek = date.getUTCDay(); // 0 (Sunday) to 6 (Saturday) // Convert JS day (Sun=0) to the application's convention (Mon=0, Sun=6) return (jsDayOfWeek === 0) ? 6 : jsDayOfWeek - 1; } /** * Calculates the previous day from a given "YYYY-MM-DD" string. * @param gameDay A string in "YYYY-MM-DD" format. * @returns The previous day as a "YYYY-MM-DD" string. */ export function getPreviousGameDay(gameDay: string): string { const date = new Date(`${gameDay}T00:00:00Z`); date.setUTCDate(date.getUTCDate() - 1); return date.toISOString().split('T')[0]; }