Wednesday, July 30, 2008

WCF DateTime field adjusted automatically for time zone

Well, I got bit by DateTime serialization yesterday. Our server is in the U.S. Central Standard Time (CST) zone and our client is in the U.S. Eastern Standard Time (EST) zone. All data saved in the database is relative to the client and NOT the server. So when the client wants to see all data for today, only the date is specified using DateTime.Today. So when the EST client sent a date of 7/29/08 00:00:00 AM to our WCF webservice on the CST server, the date was converted to 7/28/08 11:00:00 PM. The symptom from the client's point of view was that they could never retrieve data for today.

According to Coding Best Practices Using DateTime in the .NET Framework there are several ways to work around this; however, they missed one. If you change your dates so that DateTimeKind is unspecified, the XML serializer will NOT try to convert them. For example, this code will convert a date to DateTimeKind.Unspecified:

DateTime newDate = DateTime.SpecifyKind(oldDate, DateTimeKind.Unspecified);