CodexBloom - Programming Q&A Platform

implementing Date Comparison in TypeScript using Luxon for API Responses

👀 Views: 89 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-07
typescript luxon api TypeScript

I'm working on a TypeScript project that interacts with a REST API returning dates in ISO 8601 format. I'm using Luxon for date manipulation, but I'm working with issues when comparing dates from the API with the current date. For instance, I'm trying to filter out events that are happening today or in the future, but my comparisons seem to unexpected result, resulting in unexpected behavior. Here's a snippet of how I'm currently doing the comparison: ```typescript import { DateTime } from 'luxon'; const apiResponse = [ { id: 1, date: '2023-10-01T10:00:00Z' }, { id: 2, date: '2023-09-30T12:00:00Z' }, { id: 3, date: '2023-10-05T15:00:00Z' } ]; const now = DateTime.now().set({ second: 0, millisecond: 0 }); const filteredEvents = apiResponse.filter(event => { const eventDate = DateTime.fromISO(event.date); return eventDate >= now; }); ``` However, `filteredEvents` sometimes includes past events. I printed `now.toISO()` and `eventDate.toISO()` just before the comparison, and I noticed that the time zone might be affecting the comparison. My local timezone is UTC+2, which might be causing issues when the API returns dates in UTC. I've also checked that the API consistently returns an ISO string. I've tried using `eventDate.toLocal()` to convert the event date to my local timezone before comparison, but that didn't resolve the scenario either. Could someone point out if I'm missing something with date comparisons in Luxon or suggest a better approach to handle this? It seems like a common pattern but I'm puzzled by the results I'm getting. Thank you! I've been using Typescript for about a year now. Any advice would be much appreciated. I'm using Typescript LTS in this project. Any feedback is welcome!