在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
Run Code Online (Sandbox Code Playgroud)
更多在这里.
我使用此列表使用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;
Run Code Online (Sandbox Code Playgroud)
现在我遇到了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)
Run Code Online (Sandbox Code Playgroud)
更多在这里.
我找不到内置的功能来使用time zone code或time zone name在上表中给出的转换功能.
如果您乐意坚持TimeZoneInfo和DateTime/ DateTimeOffset,您可以使用Matt Johnson的TimeZoneConverter库将IANA ID(括号中的部分,例如Pacific/Kiritimati)转换为Windows系统时区ID.
项目页面文档中的示例:
string tz = TZConvert.IanaToWindows("America/New_York");
// Result: "Eastern Standard Time"
Run Code Online (Sandbox Code Playgroud)
要么:
TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("America/New_York");
Run Code Online (Sandbox Code Playgroud)
但是,需要注意的事项:
我个人建议使用我的Noda Time库,作为处理日期/时间的更简洁方式,但我承认如果你已经有很多代码处理DateTime,那可能不太可行.