views:

147

answers:

2

I am working on a C# application and want to display dates so they are local to the user's timezone. We have the user's timezone setting stored in the database, and all dates are stored in the database in UTC which should make this simple. The trick is that I also need to display the timezone offset for each date localized for the user.. The timezone offset should not be the Server's offset but the user's offset.

String timezone = (String)sessionCookie["time_zone"];
TimeZoneInfo localTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timezone);
DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDt, localTimeZone);

If i then try to do:

localDateTime.ToString("dd MMM yy - HH:mm:ss (zzz)");

I always get the offset of the server in the zzz portion rather than the offset which I just converted to.. Is there a way to use this format string but have it show the offset of the user.. I know that I can get the offset for this manually by doing:

localTimeZone.GetUtcOffset(localDateTime);

I know this is still pretty simple to format manually I was just wondering if there is a way to format the DateTime object according to a specific timezone rather than the system timezone without reinventing the wheel. The main reason is that I had utility function for converting dates from utc to the local timezone and that function did the work of getting the users timezone and what not and now i'd need to duplicate that work for the date to determine what the UtcOffset is.. I suppose the other thing I could do is have my function return the DateTime and the UtcOffset as a tuple so I don't have to duplicate the work.. Never used tuples in C# before and not sure our app supports that. Still would be nice if I could simply get the toString function to localize to a specific timezone.

+2  A: 

Try using DateTimeOffset:

DateTimeOffset utcDto = new DateTimeOffset(utcDt, TimeSpan.Zero);
DateTimeOffset localDateTime = TimeZoneInfo.ConvertTime(utcDto, localTimeZone);
string dateString = localDateTime.ToString("dd MMM yy - HH:mm:ss (zzz)");
Quartermeister
I marked this as my answer but unfortunately I realized that this isn't quite right and won't compile because ConverTime only returns a DateTime. I had figured out the answer awhile after posting the problem and using DateTimeOffset is part of the solution just not quite as you put it.
Matt Wolfe
@Matt: The overload of ConvertTime that takes a DateTimeOffset should return another DateTimeOffset: http://msdn.microsoft.com/en-us/library/bb396765.aspx
Quartermeister
A: 
     String timezone = (String)sessionCookie["time_zone"];
     DateTime dt = TimeZoneInfo.ConvertTimeFromUtc(utcDt, localTimeZone );
     TimeSpan span = localTimeZone.GetUtcOffset(utcDt)
          .Subtract(TimeZoneInfo.Local.GetUtcOffset(utcDt));
     DateTimeOffset tzOffset = new DateTimeOffset(dt, span);
     string dateString = tzOffset.ToString("dd MMM yy - HH:mm:ss (zzz)");