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?
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"}