Why can DateTime.MinValue not be serialized in timezones ahead of UTC?
Solution 1:
The main problem is DateTime.MinValue
has DateTimeKind.Unspecified
kind. It is defined as:
MinValue = new DateTime(0L, DateTimeKind.Unspecified);
But this is not a real problem, this definition leads to problem during serialization. JSON DateTime serialization done through:
System.Runtime.Serialization.Json.JsonWriterDelegator.WriteDateTime(DateTime value)
Unfortunately it is defined as:
...
if (value.Kind != DateTimeKind.Utc)
{
long num = value.Ticks - TimeZone.CurrentTimeZone.GetUtcOffset(value).Ticks;
if ((num > DateTime.MaxValue.Ticks) || (num < DateTime.MinValue.Ticks))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("JsonDateTimeOutOfRange"), new ArgumentOutOfRangeException("value")));
}
}
...
So it doesn't take into account Unspecified
and treats it as Local
. To avoid this situation you can define your own constant:
MinValueUtc = new DateTime(0L, DateTimeKind.Utc);
or
MinValueUtc = DateTime.MinValue.ToUniversalTime();
It looks weird of course, but it helps.
Solution 2:
Try to add this on any DateTime Member
[DataMember(IsRequired = false, EmitDefaultValue = false)]
Most of these erros happens because the default value of the datetime
is DateTime.MinValue
which is from year of 1 and the JSON serialization is from year 1970.