C# TimeZoneInfo 将 GMT 时区名称转换为系统时区

标签 c# .net datetime

在 Windows 中,我们得到这样的时区列表:

ID    Time zone name               Display string
--    --------------               --------------
0     Dateline Standard Time       (UTC-12:00) International Date Line West
110   UTC-11                       (UTC-11:00) Coordinated Universal Time -11
200   Hawaiian Standard Time       (UTC-10:00) Hawaii
300   Alaskan Standard Time        (UTC-09:00) Alaska

更多here .

我使用此列表从一个时区转换为另一个时区,使用 TimeZoneInfo 类接受上面列表中显示的时区名称。

例。

// Local time zone to UTC
var utcOffset = new DateTimeOffset(DateTime.UtcNow, TimeSpan.Zero);
var localTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timezoneName); // here tz name can be any name from above table
var localOffset = new DateTimeOffset(date.Value, localTimeZone.GetUtcOffset(utcOffset));
DateTime utcDate = localOffset.UtcDateTime;

现在我遇到了 SalesForce 时区表示,例如:

Time Zone Code  Time Zone Name
--------------  --------------
GMT+14:00       Line Is. Time (Pacific/Kiritimati)
GMT+13:00       Phoenix Is.Time (Pacific/Enderbury)
GMT+13:00       Tonga Time (Pacific/Tongatapu)
GMT+12:45       Chatham Standard Time (Pacific/Chatham)

更多here .

我找不到使用上表中给出的时区代码时区名称进行转换的内置功能。<​​/p>

最佳答案

如果您愿意坚持使用 TimeZoneInfoDateTime/DateTimeOffset,您可以使用 Matt Johnson 的 TimeZoneConverter将 IANA ID(括号中的部分,例如 Pacific/Kiritimati)转换为 Windows 系统时区 ID 的库。

示例来自 project page docs :

string tz = TZConvert.IanaToWindows("America/New_York");
// Result:  "Eastern Standard Time"

或者:

TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("America/New_York");

但是,需要注意的事项:

  • 不会始终存在从 IANA ID 到 Windows ID 的完整映射。有些没有映射,但情况比以前好。
  • Windows 时区数据有时可能与 IANA 数据不同。 (同样,情况正在好转。)
  • 时区数据随时间变化。如果要存储 future 日期/时间值,您可能希望存储时区和本地时间而不是 UTC 时刻。 (该时刻可能不会映射到将来的同一本地时间。)
  • 有些本地时间可能不明确 - 例如如果时钟在特定时区的特定日期从凌晨 2 点倒回到凌晨 1 点,那么当天的凌晨 1:15 将在该时区出现两次。考虑一下您希望如何处理它,并对其进行测试。

我个人建议使用我的 Noda Time库,作为处理日期/时间的一种更简洁的方式,但我承认,如果您已经有很多处理 DateTime 的代码,那可能不可行。

关于C# TimeZoneInfo 将 GMT 时区名称转换为系统时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47549107/

相关文章:

android - 每天从 sqlite 数据库获取数据 DATE TIME

c# - 如何使用LINQ获取Dictionary <string,List <Object>?

c# - 检查列表中的唯一项 (C#)

c# - 为另一个时区的服务器调整 DateTime.Now

c# - 忽略双引号内的 Rogue 引号

python - Fillna 一次使用多种方法 - pandas

c# - 如何获取存储在内存中的可执行文件的 FileVersion 信息作为字节数组?

c# - 如何最小化 Protobuf.NET 内存消耗

.net - 使用 JSON 从 AJAX 和 JQuery 调用简单的 Web 服务(.asmx 文件) - 解析错误

c++ - 十六进制的 4 字节日期时间转换为可读