Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.Net, how to serialize DateTimeOffset with 'Z' instead of +00:00, but keep other timezone offsets?

With .NET Core and Json.NET, how can I serialize a DateTimeOffset (not DateTime) so that the UTC +00:00 becomes Z while keeping any other timezone offset (-04:00 for example)?

This SO post is for DateTime, but with it, I managed to replace the +00:00 by Z while converting all timezones to UTC

new JsonSerializerSettings {
    Converters = new JsonConverter[] {
        new IsoDateTimeConverter {
            DateTimeStyles = DateTimeStyles.AdjustToUniversal,
            DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'",
        }
    }
};

I'd like to retain the timezone offset info, i.e.

2019-12-10T17:00:00Z for new DateTimeOffset(2019, 12, 10, 17, 0, 0, TimeSpan.Zero)

and

2019-12-10T13:00:00-04:00 for new DateTimeOffset(2019, 12, 10, 13, 0, 0, TimeSpan.FromHours(-4))

The DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssK" suggested works for DateTime but outputs +00:00, not Z, for DateTimeOffset...

See this .NET Fiddle for a reproduction of my attempts.

like image 352
dstj Avatar asked Dec 10 '19 22:12

dstj


1 Answers

You could subclass IsoDateTimeConverter and override CanConvert to only convert objects of type DateTimeOffset and DateTimeOffset?. Then, when DateTimeOffset.Offset is zero, output as a DateTime in universal format:

public class IsoDateTimeOffsetConverter : IsoDateTimeConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(DateTimeOffset) || objectType == typeof(DateTimeOffset?);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var dateTimeOffset = (DateTimeOffset)value;
        if (dateTimeOffset.Offset == TimeSpan.Zero)
        {
            // If there is no offset, serialize as a DateTime
            base.WriteJson(writer, dateTimeOffset.UtcDateTime, serializer);
        }
        else
        {
            base.WriteJson(writer, value, serializer);
        }
    }       
}

And then use it like so:

var settings = new JsonSerializerSettings {
    Converters = {
        new IsoDateTimeOffsetConverter(),
    }
};

Demo fiddle here.

like image 147
dbc Avatar answered Nov 08 '22 00:11

dbc