ConvertTimeFromUtc() 和 ToUniversalTime() 是否处理 DST?

Does ConvertTimeFromUtc() and ToUniversalTime() handle DST?(ConvertTimeFromUtc() 和 ToUniversalTime() 是否处理 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 the destinationTimeZone 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?

基础教程推荐