UTC to user's local time

点点圈 提交于 2019-12-12 01:37:32

问题


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.


回答1:


It's much simpler than that :)

Use TimeZoneInfo.ConvertTimeFromUtc - you don't need to mess around with offsets yourself :) (In particular, your current code assumes a DST difference of exactly one hour, which isn't always correct.)

You may want to use DateTimeOffset to avoid thinking that something's in UTC when it's not though.



来源:https://stackoverflow.com/questions/3439468/utc-to-users-local-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!