I use a legacy DMS application, who stores dates using GMT 0 (Greenwich) as default time zone and applies 1 hour spread to it. I have to display with GridView these records and I need to apply a kind of transformation according to the relative location where my system runs (as example London, Bahamas).
Looking on how the legacy system works with dates, I designed the following algorithm to display the dates properly (my code is based on asp.net / C#):
//Example for Bahamas, GMT: -5 Hours as offset, I should add 4 hours to the DB date
//Example for London, GMT: 0 Hour as offset, I should add 1 hour to the DB date
DateTime dateToDisplay;
int spreadHours = 0;
TimeZone cur = TimeZone.CurrentTimeZone;
DaylightTime daylight = cur.GetDaylightChanges(dateFromDb.Year);
DateTime start = daylight.Start;
DateTime end = daylight.End;
if (dateFromDb.CompareTo(start) <= 0 || dateFromDb.CompareTo(end) >= 0)
{
spreadHours = -1 - (cur.GetUtcOffset(dateFromDb).Hours);
}
else
{
spreadHours = - (cur.GetUtcOffset(dateFromDb).Hours);
}
dateToDisplay = dateFromDb.AddHours(spreadHours);
However I am not sure if with this process I can cover all the cases or whether there could be a better solution to achieve the same result.
Can anyone confirm my idea or suggest a better path?
In general from .NET 3.5 you could/should use the TimeZoneInfo class,
in fact to convert from an UtcDateTime to a local time all you need to do is this:
you can check this other question and answers here in SO:
Convert UTC/GMT time to local time