UTC to user's local time

2019-09-01 05:30发布

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.

标签: c# timezone
1条回答
疯言疯语
2楼-- · 2019-09-01 06:26

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.

查看更多
登录 后发表回答