I am creating a web application that will display the dates of various events that occurred in the application (for example, a document being created, for example). Of course, the displayed date should take into account the location of the user (and not just blindly display the saved date, since this will be the local time of the server).
I made an example application that lists all time zones, you can select one, and then output some saved UTC dates to your chosen time zone, adding the hour when the time zone is monitoring DST.
My question is: is this an optimal approach and / or did I miss something when this approach will not 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;
}
, , , .