Something you REALLY should know about dates ! (beeing Kind to DateTime.Kind)

September 2, 2011 / Comments Off on Something you REALLY should know about dates ! (beeing Kind to DateTime.Kind)

Here we go, some important stuff about dates…..(it’s not only BizTalk related)

I had a very simple scenario.

  1. Webservice Receives a request (with several datetime fields in it)
  2. Send the received message to SQL via the WCF adapter

For some obscure reason some datetime values  originating from the same WebRequest got modified once in the database and some did not. 
After some tracing we found that the dates were serialized in a different way once inside the webservice.
some of the formats we saw :

  • 2011-08-29T18:00:00.826;
  • 2011-08-29T18:00:00
  • 2011-08-29T18:00:00.3983714
  • 2011-08-29T18:00:00Z

All these got to the database unchanged, but we also saw datetime like below

And these datetime fields got calculated back to their UTC time and were then stored in the database.

After some experimenting we found the following interesting stuff…..

Datetime.Kind (but for sure, everybody already knew that)…. So what is this KIND ?

Public property Supported by the XNA Framework Supported by Portable Class LibraryKindGets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither.

So what happens is the following, 

  • Create a DateTime in code (like DateTime current = DateTime.Now) and Kind is Local
  • Create a DateTime in code and Assign a database field (like DateTime fromdb = datetimefield from database) and Kind = Unspecified

And what’s the difference ?

Well the difference is that when the WCF Adapter stores the date to the database field.

  • when != to unspecified it calculates it back to UTC
  • when == unspecified it is stored as is….

 

Since I really wanted unified DateTimes in the complete solution I created a pipeline that did the following trick:

        static string CreateUnspecifiedDate(string someXsDateTimeString)
        {
           DateTimeOffset dto = DateTimeOffset.Parse(someXsDateTimeString);
           DateTime res = dto.LocalDateTime;
           return System.Xml.XmlConvert.ToString(res,System.Xml.XmlDateTimeSerializationMode.Unspecified);
        }

And the problem was solved. But I did learn something about datetimes

  • Recent Posts
  • Recent Comments
  • Archives
  • Categories
  • Meta