Search code examples
jsonasp.net-coreiso8601nodatimezoneddatetime

Nodatime How do I serialize ZonedDateTime to ISO-8601 format using System.Text.Json


Is there a way to serialize a ZonedDateTime to an ISO 8601 string using System.Text.Json?

I'm currently getting output in this format 2020-03-15T15:14:53Z UTC which isn't ISO 8061 compliant.

The end goal is to feed this into Moment.js for further formatting

EDIT: Adding code snippet, noting complex, just creating a ZonedDateTime from a DateTimeOffset

//Incoming Date format "Mon Feb 10 16:46:03 +0000 2020"
var dto = DateTimeOffset.ParseExact(date, "ddd MMM dd HH:mm:ss K yyyy", CultureInfo.InvariantCulture.DateTimeFormat);
var zdt = dto.ToZonedDateTime();

Solution

  • ISO-8601 doesn't have any representation of time zones - only UTC offsets. (It's unfortunate that it refers to those as time zones, but they're not.)

    If you're constructing ZonedDateTime from a DateTimeOffset, I'd suggest not doing that, and instead using OffsetDateTime, which actually represents the information you have. (You could parse that directly from the initial value too, rather than going via DateTimeOffset.)

    While I haven't checked, I'd expect the OffsetDateTime JSON representation to be an ISO-8601 format.