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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With