[英]C# TimeZoneInfo to convert GMT timezone name to system timezone
In windows, we get timezone list like this: 在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
I use this list to convert from one timezone to another using TimeZoneInfo
class which accepts time zone name shown in above list. 我使用TimeZoneInfo
类使用该列表将一个时区转换为另一个时区,该类接受上面列表中显示的时区名称。
Ex. 例如
// 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;
Now I came across SalesForce timezone representation like: 现在,我遇到了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)
I couldn't find built in functionality to use either time zone code
or time zone name
given in above table for the conversion. 我找不到内置功能来使用上表中给出的time zone code
或time zone name
进行转换。
If you're happy to stick with TimeZoneInfo
and DateTime
/ DateTimeOffset
, you can use Matt Johnson's TimeZoneConverter
library to convert the IANA ID (the part in brackets, eg Pacific/Kiritimati) to a Windows system time zone ID. 如果您愿意坚持使用TimeZoneInfo
和DateTime
/ DateTimeOffset
,则可以使用Matt Johnson的TimeZoneConverter
库将IANA ID(括号内的部分,例如Pacific / Kiritimati)转换为Windows系统时区ID。
Examples from the project page docs : 项目页面docs中的示例:
string tz = TZConvert.IanaToWindows("America/New_York");
// Result: "Eastern Standard Time"
Or: 要么:
TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("America/New_York");
However, things to be aware of: 但是,需要注意的事项:
I'd personally recommend using my Noda Time library anyway, as a cleaner way of handling date/time, but I acknowledge that if you've got a lot of code dealing with DateTime
already, that may not be feasible. 我个人还是建议使用Noda Time库,这是一种更干净的日期/时间处理方式,但是我承认,如果您已经有很多处理DateTime
的代码,那可能不可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.