本文告诉大家在拿到任意时区的 DateTimeOffset 对象,将 DateTimeOffset 转换为使用中国的 +8 时区表示的时间

在开始之前,需要说明的是,采用 DateTimeOffset 会比 DateTime 更优的一个点是 DateTimeOffset 是带上时区的,这就意味着方便的在多个不同的时区进行传递和序列化的时候,不会丢失原来的信息

现在也推荐更多的使用 DateTimeOffset 类型而不是 DateTime 类型,除非是明确只有本机时间且后续没有需求变更才会考虑使用 DateTime 类型

可选的转换为任意国家地区的时区时间,可以是先通过 TimeZoneInfo 的 FindSystemTimeZoneById 获取到对应的国家地区的信息,如下面代码获取到中国的信息

                var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time");

这里的 FindSystemTimeZoneById 传入的 Id 可选的列表可以参阅你的本机注册表的 HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zones 的列表,详细请看 TimeZoneInfo.FindSystemTimeZoneById(String) 方法 (System) Microsoft Learn

假设能获取到 TimeZoneInfo 那可以通过 GetUtcOffset 获取对比传入的 DateTimeOffset 的时间

     var timeSpan = timeZoneInfo.GetUtcOffset(dateTimeOffset);

如此获取到的 TimeSpan 就是时区之间的差值,相加即可转换为目标国家地区的时间

                var newDateTimeOffset = dateTimeOffset + timeSpan;

以上代码拿到的 newDateTime 就是转换后的时区时间

全部的代码如下,通过以下代码即可将任意时区的时间转换为中国对应的时区的时间

                TimeZoneInfo? timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time");
                TimeSpan timeSpan = timeZoneInfo.GetUtcOffset(dateTimeOffset);

                DateTimeOffset newDateTimeOffset = dateTimeOffset + timeSpan;

修改 China Standard Time 字符串为其他国家地区的,即可转换为其他国家地区的时区

在有一些奇怪的系统上,会抛出 TimeZoneNotFoundException 异常,此时可以使用固定中国的 +8 小时作为对比 UTC 时间

此时需要先将传入的 DateTimeOffset 转换为 UTC 时间,代码如下

                DateTimeOffset utcDateTimeOffset = dateTimeOffset.ToUniversalTime();

接着直接执行 +8 小时即可转换为中国时间

                TimeSpan timeSpan = TimeSpan.FromHours(8);
                DateTimeOffset newDateTimeOffset = utcDateTimeOffset + timeSpan;

全部的代码如下

                DateTimeOffset utcDateTimeOffset = dateTimeOffset.ToUniversalTime();
                TimeSpan timeSpan = TimeSpan.FromHours(8);
                DateTimeOffset newDateTimeOffset = utcDateTimeOffset + timeSpan;

以上就是转换为中国时间的方法


本文会经常更新,请阅读原文: https://blog.lindexi.com/post/dotnet-%E5%B0%86%E4%BB%BB%E6%84%8F%E6%97%B6%E5%8C%BA%E7%9A%84-DateTimeOffset-%E8%BD%AC%E6%8D%A2%E4%B8%BA%E4%B8%AD%E5%9B%BD%E6%97%B6%E5%8C%BA%E6%97%B6%E9%97%B4%E6%96%87%E6%9C%AC.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

如果你想持续阅读我的最新博客,请点击 RSS 订阅,推荐使用RSS Stalker订阅博客,或者收藏我的博客导航

知识共享许可协议 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接: https://blog.lindexi.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系

微软最具价值专家


无盈利,不卖课,做纯粹的技术博客

以下是广告时间

推荐关注 Edi.Wang 的公众号

欢迎进入 Eleven 老师组建的 .NET 社区

以上广告全是友情推广,无盈利