Saturday, 17 August 2013

TimeZoneInfo works differently in two bits of code

TimeZoneInfo works differently in two bits of code

I have some code in my UI layer, which is supposed to take a DateTime,
which is in UTC, and convert it to a local date time:
In my Data layer, I simply do this:
private DateTime ConvertToLocal(DateTime dt)
{
if (_currentTimeZoneUser == string.Empty)
{
var u = new UserData(_userId).GetUser(_userId);
_currentTimeZoneUser = u.TimeZoneId;
}
var reply = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt,
_currentTimeZoneUser);
return reply;
}
What that does is check if _currentTimeZoneUser is set. If not, get the
zimezone from the user table, and then does a conversion.
This code is working, and I get a valid result.
I then copied the code to my UI layer (As I need to do a conversion there
as well, for a data grid), but 'reply' always equals 'dt'.
I googled, and noticed that I should be doing it a slightly different way.
So I change my UI method to this:
public static DateTime GetLocalDateTime(DateTime serverTime)
{
var timeZoneId = HttpContext.Current.Session["TimeZoneId"].ToString();
TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
var reply = TimeZoneInfo.ConvertTimeFromUtc(serverTime, cstZone);
return reply;
}
and it works!
I can't see why it works in my data layer, but in the UI, I need to change
the code.
Am I doing something wrong with my time conversion code in one of the
methods?

No comments:

Post a Comment