Thursday, November 3, 2011

ASP.NET DateTime Time Zone Management

Handling dates in ASP.NET is challenging for me.  The context of DateTime is always local time and there are no smooth transitions from SQL DateTime to a .NET DateTimeOffset.  I need to timestamp an event in the local time where it occurred and then display it to the user based on their time zone.

 

Here’s what I came up with, please tell me if there is a better way.

 

1.     I collect the event (via XML message) by sending the date in DateTime.ToString(“o”) so the timezone is saved.

 

messNow.AddXML("timestamp", DateTime.Now.ToString("o"))

 

2.     I parse the inbound XML using DateTimeOffset.TryParse so I keep the time zone and avoid DateTime’s local time assumption and then store the DateTime value to preserver local time of the event and the UTC version.

 

string TimeStamp = xmlNow.Get("timestamp");

if (!string.IsNullOrEmpty(TimeStamp))

{

   DateTimeOffset dStamp;

   if (DateTimeOffset.TryParse(TimeStamp, out dStamp))

   {

      queueNow.timestamp = dStamp.DateTime;

      queueNow.utc_timestamp = dStamp.UtcDateTime;

 

3.     I sort the event using the utc_timestamp DB column and then reconstruct the DateTimeOffset by using the TimeSpan difference.

 

            DateTimeOffset oNow = new DateTimeOffset(dLocal, dLocal - dUTC);

 

4.     You can show the DateTime local to the user by using the users local TimeSpan instead of the event’s local time.

 

 

Side Note: I’ve never liked just setting my server to UTC because it only solves a few problems, you really have to bake time zone handling into your application.

No comments:

Post a Comment