TimeZoneInfo.ConvertTimeFromUTC产生与TimeZone.BaseUTCOffset不同的输出 [英] TimeZoneInfo.ConvertTimeFromUTC produce different output then TimeZone.BaseUTCOffset

查看:79
本文介绍了TimeZoneInfo.ConvertTimeFromUTC产生与TimeZone.BaseUTCOffset不同的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UTC日期时间,我需要将其转换为EST时区.它应该像这样简单

I have a UTC date-time, I need to convert it to EST time zone. It should be as simple as this

 var easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
 var dt = DateTime.SpecifyKind(value, DateTimeKind.Utc);            
 return TimeZoneInfo.ConvertTimeFromUtc(dt, easternZone);

所以我的输入日期是

02-08-2019 22:53:32

02-08-2019 22:53:32

,结果值为

02-08-2019 18:53:32

02-08-2019 18:53:32

从给定的时间中减去4个小时.

It deduct 4 hours from given time.

但是,如果我检查了东部标准时区和UTC时区之间的偏移量,那么它返回的值为

But if I check the Offset between Eastern Standard Time Zone and UTC time zone then the value it return is

easternZone.BaseUtcOffset {-05:00:00} System.TimeSpan

easternZone.BaseUtcOffset {-05:00:00} System.TimeSpan

如果这是真的,那么上面的结果值应该是

If this is true then above result value should be

02-08-2019 17:53:32

02-08-2019 17:53:32

我不确定我在这里想念什么.

I am not sure what I am missing here.

推荐答案

我不确定我在这里想念什么.

I am not sure what I am missing here.

BaseUtcOffset 不考虑夏令时(它不能,因为它不知道您对哪个具体日期感兴趣).您可能想使用 GetUtcOffset :

返回的时间跨度包括由于应用程序而引起的任何差异调整规则到当前时区.它不同于BaseUtcOffset属性,它返回之间的区别协调世界时(UTC)和时区的标准时间因此没有考虑调整规则.

The returned time span includes any differences due to the application of adjustment rules to the current time zone. It differs from the BaseUtcOffset property, which returns the difference between Coordinated Universal Time (UTC) and the time zone's standard time and, therefore, does not take adjustment rules into account.

调整规则进行了讨论此处(强调我的意思):

Adjustment Rule is discussed here (emphasis mine):

提供有关时区调整的信息,例如 与夏令时之间的转换.

通常,如果日期比您期望的时间晚< = 1小时,请研究夏令时问题.

为了说明夏时制的影响,

To illustrate the impact of daylight saving time:

var timeUtc = Convert.ToDateTime("01-01-2019 22:53:32");
var easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
var dt = DateTime.SpecifyKind(timeUtc, DateTimeKind.Utc);            
Console.WriteLine(TimeZoneInfo.ConvertTimeFromUtc(dt, easternZone));
Console.WriteLine(easternZone.GetUtcOffset(dt));

timeUtc = Convert.ToDateTime("07-07-2019 22:53:32");
easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
dt = DateTime.SpecifyKind(timeUtc, DateTimeKind.Utc);            
Console.WriteLine(TimeZoneInfo.ConvertTimeFromUtc(dt, easternZone));
Console.WriteLine(easternZone.GetUtcOffset(dt));

上面的代码将输出:

1/1/2019 5:53:32 PM
-05:00:00
7/7/2019 6:53:32 PM
-04:00:00

这篇关于TimeZoneInfo.ConvertTimeFromUTC产生与TimeZone.BaseUTCOffset不同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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