Does ConvertTimeFromUtc() and ToUniversalTime() handle DST?(ConvertTimeFromUtc() 和 ToUniversalTime() 是否处理 DST?)
问题描述
如果夏令时生效,并且日期对象已保存到数据库(UTC 格式)中,您检索该数据库以在视图中显示它(例如 asp.net-mvc 中的视图代码>).
If daylight saving time is in effect, and a date object has been saved into the database (UTC format) which you retrieve to show it in the view (for example the view in asp.net-mvc
).
您可以使用以下方法做到这一点:
And you do that by using this method:
public static DateTime ConvertToLocalTimeFromUtcTime(DateTime utcDate, string timeZoneId)
{
TimeZoneInfo localZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(utcDate, localZone);
if (localZone.IsDaylightSavingTime(localTime))
localTime = localTime.AddHours(1); // is this needed !?
return localTime;
}
问题是,TimeZoneInfo.ConvertTimeFromUtc()
是否处理 DST,或者您是否必须自己检查并在日期对象中添加或减去 X 小时?
The question is, does TimeZoneInfo.ConvertTimeFromUtc()
handle DST's or do you have to check that yourself and either add or subtract X hour(s) to the date object?
使用 ToUniversalTime()
将日期对象转换为 UTC 格式将日期对象持久保存到数据库时的相同问题.
Same question for when persisting a date object to the database by converting it to UTC format with ToUniversalTime()
.
推荐答案
是的.ConvertTimeFromUtc
将自动处理夏令时调整,只要您定位的时区使用夏令时.
Yes. ConvertTimeFromUtc
will automatically handle daylight saving time adjustments, as long as the time zone that you are targeting uses daylight saving time.
来自 MSDN 文档:
执行转换时,ConvertTimeFromUtc
方法会应用在 destinationTimeZone
时区有效的任何调整规则.
When performing the conversion, the
ConvertTimeFromUtc
method applies any adjustment rules in effect in thedestinationTimeZone
time zone.
您应该不尝试在您的转换中增加一个小时.这会给你一个不正确的翻译.
You should not try to add an additional hour in your conversion. That will give you an incorrect translation.
关于DateTime.ToUniversalTime
,它确实考虑了夏令时,但要小心这种方法.它假定输入值在计算机的本地时区.如果您只需要使用 DateTimeKind.Utc
进行标记,请改用 DateTime.SpecifyKind
.
Regarding DateTime.ToUniversalTime
, it does take DST into account, but be careful with this method. It assumes that the input value is in the computer's local time zone. If you just need to mark it with DateTimeKind.Utc
, then use DateTime.SpecifyKind
instead.
这篇关于ConvertTimeFromUtc() 和 ToUniversalTime() 是否处理 DST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ConvertTimeFromUtc() 和 ToUniversalTime() 是否处理 DST?
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01