CodexBloom - Programming Q&A Platform

Handling DateTime Serialization with TimeZone in C# using System.Text.Json

👀 Views: 81 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-03
c# json serialization datetime dotnet6 C#

I've hit a wall trying to I am currently working on a .NET 6 Web API where I return a list of events that include `DateTime` properties... The issue arises when these events are serialized to JSON using `System.Text.Json`. The `DateTime` values are being serialized in UTC, but I need them to retain their original timezone information when sent back to the client. Here is an example of the class I'm using: ```csharp public class Event { public int Id { get; set; } public string Name { get; set; } public DateTime EventDate { get; set; } } ``` When I serialize an instance of this class, like so: ```csharp var events = new List<Event> { new Event { Id = 1, Name = "Meeting", EventDate = DateTime.Parse("2023-11-01T10:00:00-05:00") }, new Event { Id = 2, Name = "Conference", EventDate = DateTime.Parse("2023-11-05T14:00:00-05:00") } }; var jsonResult = JsonSerializer.Serialize(events); ``` The resulting JSON output looks like this: ```json [ { "Id": 1, "Name": "Meeting", "EventDate": "2023-11-01T15:00:00Z" }, { "Id": 2, "Name": "Conference", "EventDate": "2023-11-05T19:00:00Z" } ] ``` I would like the `EventDate` to remain in the format that includes the original timezone, such as "2023-11-01T10:00:00-05:00". I've tried using the `JsonSerializerOptions` to set the `DateTimeFormat` but haven't had luck, as it only affects the formatting but not the underlying UTC conversion. Here's what I have attempted so far: 1. Setting `JsonSerializerOptions` with a custom converter for `DateTime`, which didn't yield the expected results. 2. Using `DateTimeOffset` instead of `DateTime`, but I need to keep the `DateTime` structure for other parts of the application. Is there a way to configure the serialization to preserve the timezone information in the JSON output without changing my existing data structure? Is there a better approach? Thanks, I really appreciate it!