I am creating a web application that will display the dates of various events that happened within the application (like a document being produced, for instance). Of course, the date displayed needs to be considerate of where the user is located (not just blindly output the stored date, since that would be the server local time).
I've made a sample application that lists all the time zones, lets you choose one and then outputs some stored UTC dates in your selected time zone, adding an hour when the time zone is observing DST.
My question is: is this an optimal approach and/or have I missed something where by this approach won't work in all cases?
static void Main(string[] args)
{
List<DateTime> events = new List<DateTime>();
events.Add(DateTime.UtcNow);
events.Add(DateTime.UtcNow.AddDays(1));
events.Add(DateTime.UtcNow.AddDays(7));
var timeZones = TimeZoneInfo.GetSystemTimeZones();
for (var i = 0; i < timeZones.Count; i++)
{
Console.WriteLine(i + " : " + timeZones[i].DisplayName);
}
var currentZone = timeZones[Convert.ToInt32(Console.ReadLine())];
Console.WriteLine("UTC Event: {0}", events[0]);
Console.WriteLine("Local Event: {0}", correct(events[0], currentZone));
Console.ReadKey();
}
static DateTime correct(DateTime date, TimeZoneInfo timeZone)
{
var correctedDate = date.AddHours(timeZone.BaseUtcOffset.TotalHours);
if (timeZone.IsDaylightSavingTime(date))
{
return correctedDate.AddHours(1);
}
return correctedDate;
}
I'm getting the results I expect from the output, I'm just concerned that the complex issue of time zones can't be this simple to solve.