我正在尝试使用 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:00I现在处于中央时区,我们目前处于夏令时。 我想读第二行:
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:00BaseUtcOffset 显然不会根据DST进行更改。
BaseUtcOffset apparently doesn't change based on DST.
如何使用正确的偏移值获得正确的时间?
How can I get the the right time with the proper offset value?
推荐答案您需要从以下位置获取UtcOffset TimeZoneInfo,然后将其传递给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获取本地时间?
发布评论