Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you tell JSON.Net to serialize DateTime as Utc even if unspecified?

Dates in my database are stored as Utc. But when I retreieve them w/ the entity framework they come out as type unspecified.

When JSON.Net serializes them they are not in Utc format. Is there a way to tell JSON.Net to serialize DateTimes as Utc even if their type is not specified as Utc?

like image 739
C.J. Avatar asked Apr 24 '12 17:04

C.J.


1 Answers

Set DateTimeZoneHandling on JsonSerializerSettings to Utc. That will convert all dates to UTC before serializing them.

public void SerializeObjectDateTimeZoneHandling() {   string json = JsonConvert.SerializeObject(     new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),     new JsonSerializerSettings     {       DateTimeZoneHandling = DateTimeZoneHandling.Utc     });    Assert.AreEqual(@"""2000-01-01T01:01:01Z""", json); } 

Documentation: DateTimeZoneHandling setting

like image 74
James Newton-King Avatar answered Sep 18 '22 18:09

James Newton-King