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);


References:

10 comments:

Anonymous said...

In your subtitle you use the word personnel. I think you mean personal.

Assaf S. said...

Thank you for this post - it was a lifesaver!

BTW, you can use DateTime.SpecifyKind to change the Kind of an existing DateTime object

Goodman said...

I have the same problem right now. Thanks!

Anonymous said...

It is remarkable, rather amusing answer

Anonymous said...

It is remarkable, it is very valuable answer

Anonymous said...

Your blog keeps getting better and better! Your older articles are not as good as newer ones you have a lot more creativity and originality now keep it up!

cyberguest said...

good info.

and also to give some credit to the linked best practice article, the author was referring to .NET 1.0 and 1.1. back then, there was no Kind for DateTime.

Anonymous said...

Thanks 4 the post!

Anonymous said...

Very helpful thanks!

Anonymous said...

After many hours spent to understand my timezone problem, i must say you : THANK YOU !