如何在 C# 中将 UTC 时间转换为任何其他时区的时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/193731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:30:05  来源:igfitidea点击:

How to convert UTC time to Time in any other time zone in C#

c#timetimezone

提问by MSIL

I am working in C#.net - .Net fx is 2.0 which doesnot support converting between different time zones. I have wrote a scheduler based on UTC but it is giving errors of 1 hour in the DTS periods for London. I need some solution so that I can gat the correct time in any timezone relative to UTC with correct DST adjustments.

我在 C#.net 工作 - .Net fx 是 2.0,它不支持不同时区之间的转换。我写了一个基于 UTC 的调度程序,但它在伦敦的 DTS 期间给出了 1 小时的错误。我需要一些解决方案,以便我可以通过正确的 DST 调整在相对于 UTC 的任何时区中获取正确的时间。

采纳答案by Jon Skeet

Is changing to .NET 3.5 absolutely out of the question? It would make your life much, much easier. Otherwise, you're stuck with the plain TimeZone and DaylightSavings classes, as well as having to fetch the known timezones using P/Invoke.

绝对不可能更改为 .NET 3.5 吗?它会让你的生活变得更加轻松。否则,您将受困于普通的 TimeZone 和 DaylightSavings 类,并且不得不使用 P/Invoke 获取已知时区。

William Stacey has a blog post with some code to do this- but I haven't tried it, so can't vouch for its accuracy. (In my experience he's usually pretty good though :) There are no doubt similar bits of code around if that one doesn't help you.

William Stacey 有一篇博客文章,其中包含一些代码来执行此操作- 但我还没有尝试过,因此无法保证其准确性。(根据我的经验,他通常还是很不错的 :) 毫无疑问,如果那些代码对您没有帮助,就会有类似的代码。

I believe that the API he's using doesn't have access to historical data, btw. In other words, it will assume that DST alwayskicks in on the first Sunday of October (or whatever the rule is) rather than knowing that the rule has changed over time. TimeZoneInfo in .NET 3.5 supports historical data where the OS does.

我相信他使用的 API 无法访问历史数据,顺便说一句。换句话说,它会假设 DST总是在 10 月的第一个星期日(或任何规则)开始,而不是知道规则随着时间的推移而改变。.NET 3.5 中的 TimeZoneInfo 支持操作系统支持的历史数据。