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

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


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.


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.


If your time zone is GMT+1, then the UTC value of DateTime.MinValue in your time zone is going to be an hour less than DateTime.MinValue.