如何使用的TimeZoneInfo夏令时期间获取本地时间?

编程入门 行业动态 更新时间:2024-10-28 11:25:55
本文介绍了如何使用的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 savings 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 savings 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夏令时期间获取本地时间?

本文发布于:2023-11-24 18:02:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626269.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:夏令时   如何使用   时间   TimeZoneInfo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!