简体   繁体   English

有没有办法在 C# .net 中将时区格式(美国/芝加哥)转换为 UTC(-0500)?

[英]Is there a way to convert from timezone format (America/Chicago) to UTC (-0500) in C# .net?

I'm being provided a set of timezone names and need to use them as UTC offsets.我得到了一组时区名称,需要将它们用作 UTC 偏移量。 Is there a way to make this conversion to get the current UTC offset (including appropriate DST shift)?有没有办法进行这种转换以获得当前的 UTC 偏移量(包括适当的 DST 偏移)?

This is what the TimeZoneInfo.GetUtcOffset method is designed to accomplish.这就是TimeZoneInfo.GetUtcOffset方法旨在完成的任务。

DateTime utcNow = DateTime.UtcNow;
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("America/Chicago");
TimeSpan offset = tz.GetUtcOffset(utcNow);

The above will work if you are running .NET on Linux or Mac OSX, and in the future (starting with .NET 6) will work on Windows.如果您在 Linux 或 Mac OSX 上运行 .NET,以上将有效,并且在未来(从 .NET 6 开始)将适用于 ZABC46406。

If you are running .NET on Windows today, you can use my TimeZoneConverter library which will internally convert the IANA time zone ID to a Windows time zone ID when getting a TimeZoneInfo object. If you are running .NET on Windows today, you can use my TimeZoneConverter library which will internally convert the IANA time zone ID to a Windows time zone ID when getting a TimeZoneInfo object.

DateTime utcNow = DateTime.UtcNow;
TimeZoneInfo tz = TZConvert.GetTimeZoneInfo("America/Chicago");
TimeSpan offset = tz.GetUtcOffset(utcNow);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM