是否ConvertTimeFromUtc()和ToUniversalTime()处理DST? [英] Does ConvertTimeFromUtc() and ToUniversalTime() handle DST?

查看:407
本文介绍了是否ConvertTimeFromUtc()和ToUniversalTime()处理DST?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果夏令时生效,而Date对象已被保存到数据库中(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的还是你必须检查自己,无论加或减×时间(S)的日期对象?

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()

推荐答案

是的。 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 ,它确实需要DST进去,但要小心使用这种方法。它假定输入值是在计算机的本地的时区。如果你只需要使用 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆