Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to serialize DateTimeOffset to zulu time string with Json.NET?

I have a DateTimeOffset object of "05/06/2014 05:54:00 PM -04:00".

When serializing using Json.NET and ISO setting, I get "2014-05-06T17:54:00-04:00".

What I would like to have is the UTC/Zulu version of that string "2014-05-06T21:54:00Z".

However, I could not find any serializer setting to achieve this. I know for DateTime serialization, I can set DateTimeZoneHandling = DateTimeZoneHandling.Utc to have the Zulu format. However, there isn't such setting option for DateTimeOffset. Am I missing something? Or do I have to create a custom override for this?

like image 974
Zoomzoom Avatar asked May 06 '14 22:05

Zoomzoom


2 Answers

Try using the IsoDateTimeConverter that comes with Json.Net:

var date = new DateTime(2014, 5, 6, 17, 24, 55, DateTimeKind.Local);
var obj = new { date = new DateTimeOffset(date) };

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new IsoDateTimeConverter 
{ 
    DateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ", 
    DateTimeStyles = DateTimeStyles.AdjustToUniversal 
});

string json = JsonConvert.SerializeObject(obj, settings);
Console.WriteLine(json);

Output:

{"date":"2014-05-06T22:24:55Z"}
like image 109
Brian Rogers Avatar answered Oct 16 '22 13:10

Brian Rogers


You can write a custom converter like this:

class UtcDateTimeOffsetConverter : Newtonsoft.Json.Converters.IsoDateTimeConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value is DateTimeOffset)
        {
            var date = (DateTimeOffset)value;
            value = date.UtcDateTime;
        }
        base.WriteJson(writer, value, serializer);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        object value = base.ReadJson(reader, objectType, existingValue, serializer);
        if (value is DateTimeOffset)
        {
            var date = (DateTimeOffset)value;
            value = date.ToLocalTime();
        }
        return value;
    }
}

And apply it on the property you want using the JsonConverter attribute:

[JsonConverter(typeof(UtcDateTimeOffsetConverter))]
public DateTimeOffset Date { get; set; }
like image 38
Thomas Levesque Avatar answered Oct 16 '22 12:10

Thomas Levesque