Wednesday, July 25, 2012

Formatting DateTime values from another timezone

For a while I've been battling with formatting DateTime values generated in another timezone using .NET's DateTime string formatting capabilities. For instance, I have an XSD datetime value of "2012-07-26T00:00:00+10:00" (generated in Australian Eastern Standard Time), but I'm in a different timezone (Australian Central Standard Time, +09:30). If I parse the XSD datetime value into a .NET DateTime, it automatically gets converted to my timezone: "2012-07-25T23:30:00+09:30". If I then wanted to get just the date value (in the original timezone), I'd actually get the wrong date!!!

Today I finally stumbled across the DateTimeOffset class, thanks to

Basically this struct preserves the datetime in its original timezone, including offset. So for example (from LINQPad):

So, if you want to work with dates in their original timezone, DateTimeOffset is your friend!! This can be particularly important when you're working with XSD datetimes as you commonly do in BizTalk solutions, and need to format datetime values, but without converting between timezones.

No comments:

Post a Comment