Is it possible to instruct JSON.Net to serialize DateTime as UTC even if no time zone is specified?

asp.net entity-framework javascript json.net

Question

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?

1
56
4/24/2012 5:34:51 PM

Accepted Answer

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

110
6/1/2016 12:26:00 PM

Popular Answer

The response above totally works, and so I used that to create an attribute to convert an API response from PST to UTC.

First I needed to create a JsonConverter

public class UTCDateTimeConverter : Newtonsoft.Json.JsonConverter {
    private TimeZoneInfo pacificZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
    public override bool CanConvert(Type objectType) {
        return objectType == typeof(DateTime);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
        if (reader.Value == null) return null;
        var pacificTime = DateTime.Parse(reader.Value.ToString());
        return TimeZoneInfo.ConvertTimeToUtc(pacificTime, pacificZone);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
        writer.WriteValue(TimeZoneInfo.ConvertTimeFromUtc((DateTime) value, pacificZone));
    }
}

Then I had to apply that to the properties that needed to be converted

public class Order{
    [JsonConverter(typeof(UTCDateTimeConverter))]
    public DateTime OrderDate {get;set;}
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow