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?


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