Why can DateTime.MinValue not be serialized in timezones ahead of UTC?

Viewed 34938

I am experiencing issues with a WCF REST service. The wire object that I try to return has certain properties not set, resulting in DateTime.MinValue for properties of type DateTime. The service returns an empty document (with HTTP status 200 ???). When I try to call JSON serialization myself, the exception that is thrown is:

SerializationException: DateTime values that are greater than DateTime.MaxValue or smaller than DateTime.MinValue when converted to UTC cannot be serialized to JSON.

This can be reproduced by running the following code in a console app:

DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DateTime));
MemoryStream m = new MemoryStream();
DateTime dt = DateTime.MinValue;

// throws SerializationException in my timezone
ser.WriteObject(m, dt);
string json = Encoding.ASCII.GetString(m.GetBuffer());
Console.WriteLine(json);

Why is this behaviour? I think it is related to my timezone (GMT+1). As DateTime.MinValue is default(DateTime), I would expect that this can be serialized without problems.

Any tips on how to make my REST service behave? I don't want to change my DataContract.

7 Answers

It's possible to avoid the issue (with the WriteDateTimeInDefaultFormat method) by specifying a custom DateTimeFormat:

DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
settings.DateTimeFormat = new DateTimeFormat("yyyy-MM-ddThh:mm:ss.fffZ");
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(MyDataContract), settings);

Note that you should make sure that the DateTime value is really in UTC, but this is safe to use with DateTime.MinValue.

See this for additional details about the DateTimeFormat being used.

Related