Instruction file imported from KylerZan23/fitness-trackerV2 (
.cursor/rules/timezone-handling.mdc). Copyright stays with the author.
Timezone Handling for Database Queries
To ensure workout data displayed on the dashboard reflects the user's local time perception, specific database query functions in src/lib/db.ts are timezone-aware:
- Dependency: Uses the
date-fns-tzlibrary for timezone calculations. - Client Input: Functions like
getTodayWorkoutStatsandgetWorkoutTrendsaccept an IANA timezone string (e.g.,'America/Los_Angeles') as an argument, typically passed from the client component (src/app/dashboard/page.tsx) which detects it usingIntl.DateTimeFormat().resolvedOptions().timeZone. - Server-Side Calculation:
- Inside these functions, the current time (
new Date()) is converted to the user's timezone usingtoZonedTime. - The start and end of the relevant period (e.g., start/end of the user's local day for
getTodayWorkoutStats, start/end of the user's local week/month forgetWorkoutTrends) are calculated using functions likestartOfDay,endOfDay,startOfWeek,addDays. - These calculated user-local start/end times are converted back to UTC Date objects using
fromZonedTime. - The
.toISOString()representation of these UTC dates is used in the Supabase query (.gte(),.lt(),.lte()) against thecreated_atcolumn (which stores UTC timestamps).
- Inside these functions, the current time (
- Grouping/Formatting: When grouping data by date (e.g., in
getWorkoutTrends), the stored UTCcreated_attimestamp is converted back to the user's local time usingtoZonedTimebefore being formatted into ayyyy-MM-ddstring usingformatTzfromdate-fns-tz(passing thetimeZoneoption).
This ensures that queries for "today" or specific weeks/months correctly align with the user's local calendar, even though the underlying data is stored in UTC.