How to use TimeZoneInfo to get local time during Daylight Saving Time?(如何在夏令时使用 TimeZoneInfo 获取本地时间?)
问题描述
我正在尝试使用 DateTimeOffset
来传达任何时区的特定时刻.我不知道如何使用 TimeZoneInfo
来处理夏令时.
I'm trying to use DateTimeOffset
to convey a specific moment in time across any time zone. I can't figure out how to use TimeZoneInfo
to deal with daylight saving time.
var dt = DateTime.UtcNow;
Console.WriteLine(dt.ToLocalTime());
var tz = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
var utcOffset = new DateTimeOffset(dt, TimeSpan.Zero);
Console.WriteLine(utcOffset.ToOffset(tz.BaseUtcOffset));
打印出来:
6/2/2010 4:37:19 PM
6/2/2010 3:37:19 PM -06:00
我在中央时区,我们目前处于夏令时.我正在尝试阅读第二行:
I am in the central time zone, and and we are currently in daylight saving time. I am trying to get the second line to read:
6/2/2010 4:37:19 PM -05:00
BaseUtcOffset
显然不会根据 DST 改变.
BaseUtcOffset
apparently doesn't change based on DST.
我怎样才能用正确的偏移值获得正确的时间?
How can I get the the right time with the proper offset value?
推荐答案
您需要从 TimeZoneInfo 中获取 UtcOffset,然后将其传递给 ToOffset() 方法:
You need to get the UtcOffset from the TimeZoneInfo, then pass that to the ToOffset() method:
var dt = DateTime.UtcNow;
Console.WriteLine(dt.ToLocalTime());
var tz = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
var utcOffset = new DateTimeOffset(dt, TimeSpan.Zero);
Console.WriteLine(utcOffset.ToOffset(tz.GetUtcOffset(utcOffset)));
这篇关于如何在夏令时使用 TimeZoneInfo 获取本地时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在夏令时使用 TimeZoneInfo 获取本地时间?


- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04