Skip to content

Your favorite shift management application!

fix: timezone parsing for local dates (#119)

panteLd916d5998668
diff --git a/app/api/calendars/[id]/export/ics/route.ts b/app/api/calendars/[id]/export/ics/route.ts
index a929b36..296f68d 100644
--- a/app/api/calendars/[id]/export/ics/route.ts
+++ b/app/api/calendars/[id]/export/ics/route.ts
@@ -5,7 +5,7 @@ import { eq } from "drizzle-orm";
import ICAL from "ical.js";
import { getSessionUser } from "@/lib/auth/sessions";
import { canViewCalendar } from "@/lib/auth/permissions";
-import { getServerTimezone } from "@/lib/date-utils";
+import { getServerTimezone, formatDateToLocal } from "@/lib/date-utils";
export async function GET(
request: Request,
@@ -74,15 +74,13 @@ export async function GET(
}
// Set times
- const shiftDate = new Date(shift.date);
+ // shift.date is already a Date object from Drizzle (mode: "timestamp")
+ const shiftDate = shift.date as Date;
if (shift.isAllDay) {
// All-day event (DTEND is exclusive per RFC 5545)
- // Use local date methods to match how dates are stored in the database
- const year = shiftDate.getFullYear();
- const month = String(shiftDate.getMonth() + 1).padStart(2, "0");
- const day = String(shiftDate.getDate()).padStart(2, "0");
- const dateStr = `${year}-${month}-${day}`;
+ // Use formatDateToLocal to get YYYY-MM-DD format
+ const dateStr = formatDateToLocal(shiftDate);
const startTime = ICAL.Time.fromDateString(dateStr);
event.startDate = startTime;
diff --git a/app/api/calendars/[id]/export/pdf/route.ts b/app/api/calendars/[id]/export/pdf/route.ts
index bb8bf5c..9f33147 100644
--- a/app/api/calendars/[id]/export/pdf/route.ts
+++ b/app/api/calendars/[id]/export/pdf/route.ts
@@ -55,7 +55,7 @@ export async function GET(
if (month) {
const [filterYear, filterMonth] = month.split("-").map(Number);
calendarShifts = calendarShifts.filter((shift) => {
- const shiftDate = new Date(shift.date);
+ const shiftDate = shift.date as Date;
return (
shiftDate.getFullYear() === filterYear &&
shiftDate.getMonth() + 1 === filterMonth
@@ -64,7 +64,7 @@ export async function GET(
} else if (year) {
const filterYear = parseInt(year);
calendarShifts = calendarShifts.filter((shift) => {
- const shiftDate = new Date(shift.date);
+ const shiftDate = shift.date as Date;
return shiftDate.getFullYear() === filterYear;
});
}
@@ -113,7 +113,7 @@ export async function GET(
// Group shifts by month
const shiftsByMonth = new Map<string, typeof calendarShifts>();
for (const shift of calendarShifts) {
- const shiftDate = new Date(shift.date);
+ const shiftDate = shift.date as Date;
const monthKey = `${shiftDate.getFullYear()}-${String(
shiftDate.getMonth() + 1
).padStart(2, "0")}`;
@@ -150,7 +150,7 @@ export async function GET(
for (const shift of monthShifts) {
checkPageBreak(15);
- const shiftDate = new Date(shift.date);
+ const shiftDate = shift.date as Date;
const dateStr = shiftDate.toLocaleDateString(locale, {
weekday: "short",
day: "2-digit",
diff --git a/app/api/notes/route.ts b/app/api/notes/route.ts
index e0edf80..e565d88 100644
--- a/app/api/notes/route.ts
+++ b/app/api/notes/route.ts
@@ -5,6 +5,7 @@ import { eq, and, gte, lte } from "drizzle-orm";
import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";
import { getSessionUser } from "@/lib/auth/sessions";
import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";
+import { parseLocalDate } from "@/lib/date-utils";
// GET calendar notes for a calendar (with optional date filter)
export async function GET(request: Request) {
@@ -49,9 +50,19 @@ export async function GET(request: Request) {
.where(eq(calendarNotes.calendarId, calendarId));
if (date) {
- const targetDate = new Date(date);
- const startOfDay = new Date(targetDate.setHours(0, 0, 0, 0));
- const endOfDay = new Date(targetDate.setHours(23, 59, 59, 999));
+ let targetDate;
+ try {
+ targetDate = parseLocalDate(date);
+ } catch {
+ return NextResponse.json(
+ { error: "Invalid date format" },
+ { status: 400 }
+ );
+ }
+ const startOfDay = new Date(targetDate);
+ startOfDay.setHours(0, 0, 0, 0);
+ const endOfDay = new Date(targetDate);
+ endOfDay.setHours(23, 59, 59, 999);
const result = await db
.select()
@@ -129,11 +140,21 @@ export async function POST(request: Request) {
);
}
+ let parsedDate;
+ try {
+ parsedDate = parseLocalDate(date);
+ } catch {
+ return NextResponse.json(
+ { error: "Invalid date format" },
+ { status: 400 }
+ );
+ }
+
const [calendarNote] = await db
.insert(calendarNotes)
.values({
calendarId,
- date: new Date(date),
+ date: parsedDate,
note,
type: type || "note",
color: color || null,
diff --git a/app/api/shifts/[id]/route.ts b/app/api/shifts/[id]/route.ts
index 56f484d..ebab39c 100644
--- a/app/api/shifts/[id]/route.ts
+++ b/app/api/shifts/[id]/route.ts
@@ -5,6 +5,7 @@ import { eq } from "drizzle-orm";
import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";
import { getSessionUser } from "@/lib/auth/sessions";
import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";
+import { parseLocalDate } from "@/lib/date-utils";
// GET single shift
export async function GET(
@@ -116,7 +117,7 @@ export async function PATCH(
}
const updateData: Partial<typeof shifts.$inferInsert> = {};
- if (date) updateData.date = new Date(date);
+ if (date) updateData.date = parseLocalDate(date);
if (startTime !== undefined) updateData.startTime = startTime;
if (endTime !== undefined) updateData.endTime = endTime;
if (title) updateData.title = title;
diff --git a/app/api/shifts/route.ts b/app/api/shifts/route.ts
index 68f2f12..115e9ec 100644
--- a/app/api/shifts/route.ts
+++ b/app/api/shifts/route.ts
@@ -5,6 +5,7 @@ import { eq, and, gte, lte, or, isNull } from "drizzle-orm";
import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";
import { getSessionUser } from "@/lib/auth/sessions";
import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";
+import { parseLocalDate } from "@/lib/date-utils";
// GET shifts for a calendar (with optional date filter)
export async function GET(request: Request) {
@@ -71,9 +72,19 @@ export async function GET(request: Request) {
.leftJoin(externalSyncs, eq(shifts.externalSyncId, externalSyncs.id));
if (date) {
- const targetDate = new Date(date);
- const startOfDay = new Date(targetDate.setHours(0, 0, 0, 0));
- const endOfDay = new Date(targetDate.setHours(23, 59, 59, 999));
+ let targetDate;
+ try {
+ targetDate = parseLocalDate(date);
+ } catch {
+ return NextResponse.json(
+ { error: "Invalid date format" },
+ { status: 400 }
+ );
+ }
+ const startOfDay = new Date(targetDate);
+ startOfDay.setHours(0, 0, 0, 0);
+ const endOfDay = new Date(targetDate);
+ endOfDay.setHours(23, 59, 59, 999);
const result = await query.where(
and(
@@ -152,12 +163,22 @@ export async function POST(request: Request) {
);
}
+ let parsedDate;
+ try {
+ parsedDate = parseLocalDate(date);
+ } catch {
+ return NextResponse.json(
+ { error: "Invalid date format" },
+ { status: 400 }
+ );
+ }
+
const [shift] = await db
.insert(shifts)
.values({
calendarId,
presetId: presetId || null,
- date: new Date(date),
+ date: parsedDate,
startTime: isAllDay ? "00:00" : startTime,
endTime: isAllDay ? "23:59" : endTime,
title,
diff --git a/app/page.tsx b/app/page.tsx
index 1b66402..cfe233f 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -16,9 +16,9 @@ import {
Shift,
} from "@/lib/db/schema";
import { useCalendars } from "@/hooks/useCalendars";
-import { useShifts } from "@/hooks/useShifts";
+import { useShifts, normalizeShift } from "@/hooks/useShifts";
import { usePresets } from "@/hooks/usePresets";
-import { useNotes } from "@/hooks/useNotes";
+import { useNotes, normalizeNote } from "@/hooks/useNotes";
import { useSSEConnection } from "@/hooks/useSSEConnection";
import { useViewSettings } from "@/hooks/useViewSettings";
import { useShiftActions } from "@/hooks/useShiftActions";
@@ -37,7 +37,7 @@ import { AppFooter } from "@/components/app-footer";
import { AppHeader } from "@/components/app-header";
import { DialogManager } from "@/components/dialog-manager";
import { getCalendarDays } from "@/lib/calendar-utils";
-import { formatDateToLocal } from "@/lib/date-utils";
+import { formatDateToLocal, parseLocalDate } from "@/lib/date-utils";
import { findNotesForDate } from "@/lib/event-utils";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
@@ -316,8 +316,8 @@ function HomeContent() {
]);
dataMap.set(calendarId, {
- shifts: shiftsData,
- notes: notesData,
+ shifts: shiftsData.map(normalizeShift),
+ notes: notesData.map(normalizeNote),
externalSyncs: syncsData,
presets: presetsData,
togglingDates: new Set<string>(),
@@ -411,39 +411,54 @@ function HomeContent() {
};
// Day interaction handlers
- const handleDayClick = (date: Date) => {
- shiftActions.handleAddShift(date, selectedPresetId);
+ const handleDayClick = (date: Date | string) => {
+ // Parse date to ensure it's a Date object
+ const targetDate =
+ typeof date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(date)
+ ? parseLocalDate(date)
+ : new Date(date);
+ shiftActions.handleAddShift(targetDate, selectedPresetId);
};
- const handleDayRightClick = (e: React.MouseEvent, date: Date) => {
+ const handleDayRightClick = (e: React.MouseEvent, date: Date | string) => {
e.preventDefault();
+ // Parse date to ensure it's a Date object
+ const targetDate =
+ typeof date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(date)
+ ? parseLocalDate(date)
+ : new Date(date);
// Get all notes/events for this date (including recurring)
- const allDayNotes = findNotesForDate(notes, date);
+ const allDayNotes = findNotesForDate(notes, targetDate);
// Always show list dialog when notes exist (to allow adding more)
if (allDayNotes.length >= 1) {
- dialogStates.setSelectedDayDate(date);
+ dialogStates.setSelectedDayDate(targetDate);
dialogStates.setSelectedDayNotes(allDayNotes);
dialogStates.setShowNotesListDialog(true);
} else {
// No notes - show note edit dialog to create new
- noteActions.openNoteDialog(date, undefined);
+ noteActions.openNoteDialog(targetDate, undefined);
}
};
- const handleNoteIconClick = (e: React.MouseEvent, date: Date) => {
+ const handleNoteIconClick = (e: React.MouseEvent, date: Date | string) => {
e.stopPropagation();
+ // Parse date to ensure it's a Date object
+ const targetDate =
+ typeof date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(date)
+ ? parseLocalDate(date)
+ : new Date(date);
// Get all notes/events for this date (including recurring)
- const allDayNotes = findNotesForDate(notes, date);
+ const allDayNotes = findNotesForDate(notes, targetDate);
// Always show list dialog when notes exist (to allow adding more)
if (allDayNotes.length >= 1) {
- dialogStates.setSelectedDayDate(date);
+ dialogStates.setSelectedDayDate(targetDate);
dialogStates.setSelectedDayNotes(allDayNotes);
dialogStates.setShowNotesListDialog(true);
} else {
// No notes - show note edit dialog to create new
- noteActions.openNoteDialog(date, undefined);
+ noteActions.openNoteDialog(targetDate, undefined);
}
};
@@ -514,18 +529,27 @@ function HomeContent() {
};
// Compare mode interaction handlers
- const handleCompareDayClick = async (calendarId: string, date: Date) => {
+ const handleCompareDayClick = async (
+ calendarId: string,
+ date: Date | string
+ ) => {
+ // Always parse date to ensure it's a Date object
+ const targetDate =
+ typeof date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(date)
+ ? parseLocalDate(date)
+ : new Date(date);
+
if (!selectedPresetId) {
// No preset selected, just show existing shifts if any
const calendarData = compareCalendarData.get(calendarId);
if (!calendarData) return;
const dayShifts = calendarData.shifts.filter(
- (shift) => shift.date && isSameDay(new Date(shift.date), date)
+ (shift) => shift.date && isSameDay(shift.date as Date, targetDate)
);
if (dayShifts.length > 0) {
- dialogStates.setSelectedDayDate(date);
+ dialogStates.setSelectedDayDate(targetDate);
dialogStates.setSelectedDayShifts(dayShifts);
dialogStates.setShowDayShiftsDialog(true);
}
@@ -539,7 +563,6 @@ function HomeContent() {
const preset = calendarData.presets.find((p) => p.id === selectedPresetId);
if (!preset) return;
- const targetDate = new Date(date);
const dateKey = formatDateToLocal(targetDate);
// Check if already toggling
@@ -562,7 +585,7 @@ function HomeContent() {
const existingShift = calendarData.shifts.find(
(shift) =>
shift.date &&
- isSameDay(new Date(shift.date), targetDate) &&
+ isSameDay(shift.date as Date, targetDate) &&
shift.title === preset.title &&
shift.startTime === preset.startTime &&
shift.endTime === preset.endTime
@@ -586,7 +609,10 @@ function HomeContent() {
const updated = new Map(prev);
const data = updated.get(calendarId);
if (data) {
- updated.set(calendarId, { ...data, shifts: shiftsData });
+ updated.set(calendarId, {
+ ...data,
+ shifts: shiftsData.map(normalizeShift),
+ });
}
return updated;
});
@@ -623,7 +649,10 @@ function HomeContent() {
const updated = new Map(prev);
const data = updated.get(calendarId);
if (data) {
- updated.set(calendarId, { ...data, shifts: shiftsData });
+ updated.set(calendarId, {
+ ...data,
+ shifts: shiftsData.map(normalizeShift),
+ });
}
return updated;
});
@@ -860,7 +889,7 @@ function HomeContent() {
updated.set(calendarId, {
...data,
presets: presetsData,
- shifts: shiftsData,
+ shifts: shiftsData.map(normalizeShift),
});
}
return updated;
@@ -904,7 +933,7 @@ function HomeContent() {
if (currentData) {
dataMap.set(calendarId, {
...currentData,
- shifts: shiftsData,
+ shifts: shiftsData.map(normalizeShift),
});
}
}
diff --git a/components/calendar-grid.tsx b/components/calendar-grid.tsx
index 647bfe0..fb45980 100644
--- a/components/calendar-grid.tsx
+++ b/components/calendar-grid.tsx
@@ -73,7 +73,7 @@ export function CalendarGrid({
const getShiftsForDate = (date: Date) => {
return shifts.filter(
- (shift) => shift.date && isSameDay(new Date(shift.date), date)
+ (shift) => shift.date && isSameDay(shift.date as Date, date)
);
};
diff --git a/components/shifts-list.tsx b/components/shifts-list.tsx
index 2c5feaa..2c15921 100644
--- a/components/shifts-list.tsx
+++ b/components/shifts-list.tsx
@@ -32,7 +32,7 @@ export function ShiftsList({
const shiftsInMonth = shifts.filter((shift) => {
if (!shift.date) return false;
- const shiftDate = new Date(shift.date);
+ const shiftDate = shift.date as Date;
return (
shiftDate.getMonth() === currentDate.getMonth() &&
shiftDate.getFullYear() === currentDate.getFullYear()
@@ -42,12 +42,12 @@ export function ShiftsList({
const groupedShifts = shiftsInMonth
.sort(
(a, b) =>
- (a.date ? new Date(a.date).getTime() : 0) -
- (b.date ? new Date(b.date).getTime() : 0)
+ (a.date ? (a.date as Date).getTime() : 0) -
+ (b.date ? (b.date as Date).getTime() : 0)
)
.reduce((acc, shift) => {
const dateKey = shift.date
- ? format(new Date(shift.date), "yyyy-MM-dd")
+ ? format(shift.date as Date, "yyyy-MM-dd")
: "unknown";
if (!acc[dateKey]) acc[dateKey] = [];
acc[dateKey].push(shift);
@@ -145,7 +145,7 @@ export function ShiftsList({
<div className="w-1 h-5 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>
{dayShifts[0].date &&
format(
- new Date(dayShifts[0].date),
+ dayShifts[0].date as Date,
"EEEE, MMMM d, yyyy",
{ locale: dateLocale }
)}
diff --git a/hooks/useNotes.ts b/hooks/useNotes.ts
index 423e97c..a2b1df3 100644
--- a/hooks/useNotes.ts
+++ b/hooks/useNotes.ts
@@ -1,9 +1,25 @@
import { useState, useEffect, useCallback } from "react";
import { useTranslations } from "next-intl";
import { CalendarNote } from "@/lib/db/schema";
-import { formatDateToLocal } from "@/lib/date-utils";
+import { formatDateToLocal, parseLocalDate } from "@/lib/date-utils";
import { toast } from "sonner";
+// Helper to convert API response timestamps to Date objects
+export function normalizeNote(note: Record<string, unknown>): CalendarNote {
+ const dateValue = note.date as string | number | Date;
+ const parsedDate =
+ typeof dateValue === "string" && /^\d{4}-\d{2}-\d{2}$/.test(dateValue)
+ ? parseLocalDate(dateValue)
+ : new Date(dateValue);
+
+ return {
+ ...(note as Omit<CalendarNote, "date" | "createdAt" | "updatedAt">),
+ date: parsedDate,
+ createdAt: new Date(note.createdAt as string | number | Date),
+ updatedAt: new Date(note.updatedAt as string | number | Date),
+ };
+}
+
export function useNotes(calendarId: string | undefined) {
const t = useTranslations();
const [notes, setNotes] = useState<CalendarNote[]>([]);
@@ -28,7 +44,7 @@ export function useNotes(calendarId: string | undefined) {
return;
}
const data = await response.json();
- setNotes(data);
+ setNotes(data.map(normalizeNote));
} catch (error) {
// Network errors or other exceptions - don't clear existing notes
console.error("Failed to fetch notes:", error);
diff --git a/hooks/useShiftActions.ts b/hooks/useShiftActions.ts
index a210d28..1b86ec8 100644
--- a/hooks/useShiftActions.ts
+++ b/hooks/useShiftActions.ts
@@ -5,7 +5,7 @@ import { isSameDay } from "date-fns";
import { ShiftFormData } from "@/components/shift-sheet";
import { ShiftWithCalendar } from "@/lib/types";
import { ShiftPreset } from "@/lib/db/schema";
-import { formatDateToLocal } from "@/lib/date-utils";
+import { formatDateToLocal, parseLocalDate } from "@/lib/date-utils";
interface UseShiftActionsProps {
shifts: ShiftWithCalendar[];
@@ -70,13 +70,16 @@ export function useShiftActions({
);
const handleAddShift = useCallback(
- async (date: Date, selectedPresetId: string | undefined) => {
+ async (date: Date | string, selectedPresetId: string | undefined) => {
if (!selectedPresetId) return;
const preset = presets.find((p) => p.id === selectedPresetId);
if (!preset) return;
- const targetDate = new Date(date);
+ const targetDate =
+ typeof date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(date)
+ ? parseLocalDate(date)
+ : new Date(date);
const dateKey = formatDateToLocal(targetDate);
if (togglingDatesRef.current.has(dateKey)) return;
@@ -87,7 +90,7 @@ export function useShiftActions({
const existingShift = shifts.find(
(shift) =>
shift.date &&
- isSameDay(new Date(shift.date), targetDate) &&
+ isSameDay(shift.date as Date, targetDate) &&
shift.title === preset.title &&
shift.startTime === preset.startTime &&
shift.endTime === preset.endTime
diff --git a/hooks/useShifts.ts b/hooks/useShifts.ts
index 33dc1e6..96ac6f0 100644
--- a/hooks/useShifts.ts
+++ b/hooks/useShifts.ts
@@ -3,6 +3,25 @@ import { ShiftWithCalendar } from "@/lib/types";
import { ShiftFormData } from "@/components/shift-sheet";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
+import { parseLocalDate } from "@/lib/date-utils";
+
+// Helper to convert API response timestamps to Date objects
+export function normalizeShift(
+ shift: Record<string, unknown>
+): ShiftWithCalendar {
+ const dateValue = shift.date as string | number | Date;
+ const parsedDate =
+ typeof dateValue === "string" && /^\d{4}-\d{2}-\d{2}$/.test(dateValue)
+ ? parseLocalDate(dateValue)
+ : new Date(dateValue);
+
+ return {
+ ...(shift as Omit<ShiftWithCalendar, "date" | "createdAt" | "updatedAt">),
+ date: parsedDate,
+ createdAt: new Date(shift.createdAt as string | number | Date),
+ updatedAt: new Date(shift.updatedAt as string | number | Date),
+ };
+}
export function useShifts(calendarId: string | undefined) {
const t = useTranslations();
@@ -26,7 +45,7 @@ export function useShifts(calendarId: string | undefined) {
return;
}
const data = await response.json();
- setShifts(data);
+ setShifts(data.map(normalizeShift));
setHasLoadedOnce(true);
} catch (error) {
console.error("Failed to fetch shifts:", error);
@@ -46,7 +65,7 @@ export function useShifts(calendarId: string | undefined) {
const tempId = `temp-${Date.now()}`;
const optimisticShift: ShiftWithCalendar = {
id: tempId,
- date: new Date(formData.date),
+ date: parseLocalDate(formData.date),
startTime: formData.startTime,
endTime: formData.endTime,
title: formData.title,
@@ -83,10 +102,10 @@ export function useShifts(calendarId: string | undefined) {
const newShift = await response.json();
setShifts((shifts) =>
- shifts.map((s) => (s.id === tempId ? newShift : s))
+ shifts.map((s) => (s.id === tempId ? normalizeShift(newShift) : s))
);
toast.success(t("common.created", { item: t("shift.shift_one") }));
- return newShift;
+ return normalizeShift(newShift);
} catch (error) {
console.error("Failed to create shift:", error);
setShifts((shifts) => shifts.filter((s) => s.id !== tempId));
diff --git a/lib/date-utils.ts b/lib/date-utils.ts
index a305a01..dcb474b 100644
--- a/lib/date-utils.ts
+++ b/lib/date-utils.ts
@@ -9,6 +9,85 @@ export function formatDateToLocal(date: Date): string {
return `${year}-${month}-${day}`;
}
+/**
+ * Parses a YYYY-MM-DD date string as a local date (NOT UTC!)
+ * This fixes the timezone bug where "2025-01-15" was interpreted as UTC midnight
+ * @param dateString - Date string in YYYY-MM-DD format
+ * @returns Date object representing local midnight on that date
+ * @throws TypeError if dateString is not a valid YYYY-MM-DD format or represents an invalid date
+ * @example
+ * parseLocalDate("2025-01-15") // → Wed Jan 15 2025 00:00:00 (local timezone)
+ * new Date("2025-01-15") // → Tue Jan 14 2025 19:00:00 (UTC-5, WRONG!)
+ */
+export function parseLocalDate(dateString: string): Date {
+ // 1. Ensure dateString is a non-empty string
+ if (typeof dateString !== "string" || dateString.trim() === "") {
+ throw new TypeError("Invalid date format: expected non-empty string");
+ }
+
+ // 2. Match strict YYYY-MM-DD pattern
+ const datePattern = /^\d{4}-\d{2}-\d{2}$/;
+ if (!datePattern.test(dateString)) {
+ throw new TypeError(
+ `Invalid date format: expected YYYY-MM-DD, got "${dateString}"`
+ );
+ }
+
+ // 3. Parse year/month/day as numbers
+ const [year, month, day] = dateString.split("-").map(Number);
+
+ // 4. Validate month is 1-12
+ if (month < 1 || month > 12) {
+ throw new TypeError(
+ `Invalid date: month must be 1-12, got ${month} in "${dateString}"`
+ );
+ }
+
+ // 5. Validate day is within valid range for that month (account for leap years)
+ const daysInMonth = [
+ 31, // January
+ isLeapYear(year) ? 29 : 28, // February
+ 31, // March
+ 30, // April
+ 31, // May
+ 30, // June
+ 31, // July
+ 31, // August
+ 30, // September
+ 31, // October
+ 30, // November
+ 31, // December
+ ];
+
+ const maxDay = daysInMonth[month - 1];
+ if (day < 1 || day > maxDay) {
+ throw new TypeError(
+ `Invalid date: day must be 1-${maxDay} for month ${month}, got ${day} in "${dateString}"`
+ );
+ }
+
+ // 6. Construct the Date and verify it's not NaN
+ // month is 0-indexed in Date constructor
+ const date = new Date(year, month - 1, day);
+ if (isNaN(date.getTime())) {
+ throw new TypeError(`Invalid date: could not parse "${dateString}"`);
+ }
+
+ return date;
+}
+
+/**
+ * Checks if a year is a leap year
+ * @param year - The year to check
+ * @returns true if the year is a leap year
+ */
+function isLeapYear(year: number): boolean {
+ // A year is a leap year if:
+ // - It's divisible by 4 AND
+ // - Either not divisible by 100 OR divisible by 400
+ return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
+}
+
/**
* Calculates the duration in minutes between two time strings
* @param startTime - Time string in HH:MM format
diff --git a/lib/event-utils.ts b/lib/event-utils.ts
index 374fd32..7c70471 100644
--- a/lib/event-utils.ts
+++ b/lib/event-utils.ts
@@ -1,4 +1,5 @@
import { CalendarNote } from "./db/schema";
+import { parseLocalDate } from "./date-utils";
export function matchesRecurringEvent(
eventDate: Date,
@@ -76,7 +77,13 @@ export function findEventsForDate(
): CalendarNote[] {
return notes.filter((note) => {
if (note.type !== "event" || !note.date) return false;
- const noteDate = new Date(note.date);
+ const dateValue = note.date;
+ const noteDate =
+ dateValue instanceof Date
+ ? dateValue
+ : typeof dateValue === "string" && /^\d{4}-\d{2}-\d{2}$/.test(dateValue)
+ ? parseLocalDate(dateValue)
+ : new Date(dateValue);
// Exact date match
if (
@@ -104,7 +111,13 @@ export function findNotesForDate(
): CalendarNote[] {
return notes.filter((note) => {
if (!note.date) return false;
- const noteDate = new Date(note.date);
+ const dateValue = note.date;
+ const noteDate =
+ dateValue instanceof Date
+ ? dateValue
+ : typeof dateValue === "string" && /^\d{4}-\d{2}-\d{2}$/.test(dateValue)
+ ? parseLocalDate(dateValue)
+ : new Date(dateValue);
// Exact date match
if (
@@ -128,18 +141,3 @@ export function findNotesForDate(
return false;
});
}
-
-// Legacy functions for backwards compatibility - return first match
-export function findEventForDate(
- notes: CalendarNote[],
- date: Date
-): CalendarNote | undefined {
- return findEventsForDate(notes, date)[0];
-}
-
-export function findNoteForDate(
- notes: CalendarNote[],
- date: Date
-): CalendarNote | undefined {
- return findNotesForDate(notes, date)[0];
-}
diff --git a/lib/external-calendar-utils.ts b/lib/external-calendar-utils.ts
index 310729a..8614ee4 100644
--- a/lib/external-calendar-utils.ts
+++ b/lib/external-calendar-utils.ts
@@ -4,6 +4,7 @@
*/
import ICAL from "ical.js";
+import { formatDateToLocal } from "./date-utils";
export type CalendarSyncType = "icloud" | "google" | "custom";
@@ -116,14 +117,6 @@ export function isValidICSContent(icsContent: string): boolean {
}
}
-/**
- * Backwards compatibility - validates iCloud URLs
- * @deprecated Use isValidCalendarUrl instead
- */
-export function isValidICloudUrl(url: string): boolean {
- return isValidCalendarUrl(url, "icloud");
-}
-
/**
* Expands recurring events into individual occurrences within a time window
* @param vevent - The VEVENT component from iCal.js
@@ -387,8 +380,9 @@ export function needsUpdate(
}
): boolean {
// Compare date (convert to comparable format)
- const existingDate = new Date(existing.date).toISOString().split("T")[0];
- const newDate = new Date(newData.date).toISOString().split("T")[0];
+ // existing.date is a Date from Drizzle
+ const existingDate = formatDateToLocal(existing.date as Date);
+ const newDate = formatDateToLocal(newData.date);
if (existingDate !== newDate) return true;
// Compare time fields
diff --git a/lib/rate-limiter.ts b/lib/rate-limiter.ts
index d21225e..0a6de73 100644
--- a/lib/rate-limiter.ts
+++ b/lib/rate-limiter.ts
@@ -508,45 +508,3 @@ export function getRateLimitStatus(
remaining === 0 ? Math.ceil((entry.resetAt - now) / 1000) : undefined,
};
}
-
-/**
- * Manually reset rate limit for a specific identifier
- * Useful for testing or administrative purposes
- */
-export function resetRateLimit(identifier: string): void {
- // Remove all entries matching the identifier prefix
- const keysToDelete: string[] = [];
- for (const key of store.keys()) {
- if (key.startsWith(identifier)) {
- keysToDelete.push(key);
- }
- }
- keysToDelete.forEach((key) => store.delete(key));
-}
-
-/**
- * Get stats about the rate limiter (for monitoring/debugging)
- */
-export function getRateLimiterStats(): {
- totalEntries: number;
- activeEntries: number;
- expiredEntries: number;
-} {
- const now = Date.now();
- let activeEntries = 0;
- let expiredEntries = 0;
-
- for (const entry of store.values()) {
- if (entry.resetAt > now) {
- activeEntries++;
- } else {
- expiredEntries++;
- }
- }
-
- return {
- totalEntries: store.size,
- activeEntries,
- expiredEntries,
- };
-}
diff --git a/lib/version.ts b/lib/version.ts
index a2007ca..45101ce 100644
--- a/lib/version.ts
+++ b/lib/version.ts
@@ -129,15 +129,6 @@ export async function getCurrentVersion(): Promise<string> {
return buildInfo.version;
}
-/**
- * Get current application version (sync - for backwards compatibility)
- * Returns cached version if available, otherwise returns "loading..."
- * @deprecated Use getCurrentVersion() async function instead
- */
-export function getCurrentVersionSync(): string {
- return cachedBuildInfo?.version || "loading...";
-}
-
/**
* Build GitHub URL for a version
*/