次の方法で共有


DateTime Json serialization with Min and Max values

This one tripped me this week - although the MSDN doc for MinValue and MaxValue will tell you "UTC", they aren't truly that. They are declared as kind 'unspecified' rather than UTC, which will lead to somewhat unexpected results in Json serialization. If like us you enable internally the DateTimeStyles.AdjustToUniversal of Newtonsoft.Json.Converters' IsoDateTimeConverter, during Json serialization DateTime::ToUniversalTime() will be called. As the kind is unspecified "The current DateTime object is assumed to be a local time, and the conversion is performed as if Kind were Local." Oops. Here in Seattle's PST, 0001-01-01T00:00:00.0000000Z suddenly became 0001-01-01T08:00:00.0000000Z, etc.

So, just like you should use DateTime.UtcNow over DateTime.Now, you should also use new DateTime(0L, DateTimeKind.Utc) over DateTime.MinValue and use new DateTime(3155378975999999999L, DateTimeKind.Utc) over DateTime.MaxValue to avoid surprises going over the wire between clients and servers distributed around the world.

Comments

  • Anonymous
    March 27, 2017
    Added this one to my bookmarks. Thanks!
  • Anonymous
    June 20, 2019
    This blog has been moved off the MSDN platform. Find further content and update at https://www.linkedin.com/today/author/daviburgComments are locked as part of the blog migration, so please reach out to your customer support contact for assistance with Microsoft products and services.