UTC 到用户本地时间 [英] UTC to user's local time

查看:37
本文介绍了UTC 到用户本地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 Web 应用程序,它将显示应用程序中发生的各种事件的日期(例如正在生成的文档).当然,显示的日期需要考虑用户所在的位置(不要盲目输出存储的日期,因为那会是服务器本地时间).

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).

我制作了一个示例应用程序,其中列出了所有时区,让您选择一个,然后在您选择的时区输出一些存储的 UTC 日期,在时区遵守 DST 时添加一个小时.

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.

推荐答案

比那简单多了 :)

使用 TimeZoneInfo.ConvertTimeFromUtc - 您不需要自己处理偏移量 :) (特别是,您当前的代码假设夏令时差正好是一小时,这并不总是正确的.)

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.)

您可能希望使用 DateTimeOffset 来避免认为某些内容在 UTC 中,但实际上并非如此.

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

这篇关于UTC 到用户本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆