CodexBloom - Programming Q&A Platform

Sorting an Array of Employee Objects by Hire Date with Timezone Considerations in TypeScript

👀 Views: 0 💬 Answers: 1 📅 Created: 2025-08-22
typescript sorting dates TypeScript

I'm migrating some code and Could someone explain I'm a bit lost with I've searched everywhere and can't find a clear answer..... I'm working with a scenario while trying to sort an array of employee objects by their hire dates, which are stored as strings in ISO 8601 format. Some of these hire dates include timezone offsets, while others are in UTC. Here's a snippet of my employee array: ```typescript const employees = [ { name: 'Alice', hireDate: '2021-05-30T14:00:00Z' }, { name: 'Bob', hireDate: '2020-10-15T09:30:00-05:00' }, { name: 'Charlie', hireDate: '2022-01-25T10:00:00+00:00' }, { name: 'Diana', hireDate: '2021-05-30T09:00:00-08:00' } ]; ``` When I try to sort this array using the following code: ```typescript const sortedEmployees = employees.sort((a, b) => { return new Date(a.hireDate).getTime() - new Date(b.hireDate).getTime(); }); ``` I expect to get a sorted array in ascending order based on the hire dates. However, I'm running into an scenario where the order seems to be inconsistent, especially with the timezone offsets. For example, I end up with `Diana` appearing earlier than `Alice`, which should not be the case as her hire date is earlier in UTC. I’ve checked the parsed dates in the console and they appear correct, but the sorting logic seems flawed. I’ve also considered using a library like `date-fns` or `moment.js`, but I’d prefer a native solution if possible. Is there something I’m missing in the sorting logic, or is there a better approach to handle this scenario? Any insights would be greatly appreciated! Am I approaching this the right way? I'm working on a microservice that needs to handle this. Hoping someone can shed some light on this. My development environment is Linux. Thanks in advance! This is happening in both development and production on CentOS.