中欧是否有通用的TimeZoneInfo? [英] Is there a generic TimeZoneInfo For Central Europe?
问题描述
中欧是否存在将CET和CEST都考虑在内的通用TimeZoneInfo?
Is there a generic TimeZoneInfo for Central Europe that takes into consideration both CET and CEST into one?
我有一个执行以下操作的应用程序:
I have an app that is doing the following:
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
DateTimeOffset dto = new DateTimeOffset(someDate, tzi.BaseUtcOffset);
var utcDate = dto.ToUniversalTime().DateTime;
问题在于这会返回错误的utcDate,因为BaseUtcOffset是+1而不是+2。看来CET也具有DST,并且取决于一年中的时间,它为+1或+2。
The problem is that this is returning the wrong utcDate because the BaseUtcOffset is +1 instead of +2. It appears that CET has DST as well and depending on the time of the year it is +1 or +2.
推荐答案
首先,我要赞扬mgnoonan使用Noda Time的答案:)但是,如果您不喜欢冒险。 ..
Firstly, I'd like to applaud mgnoonan's answer of using Noda Time :) But if you're feeling less adventurous...
您已经在使用正确的时区-但您不应该使用 BaseUtcOffset
(已记录)关于DST:
You're already using the right time zone - but you shouldn't be using BaseUtcOffset
which is documented not to be about DST:
获取当前时区的标准时间与协调世界时(UTC)之间的时差。
Gets the time difference between the current time zone's standard time and Coordinated Universal Time (UTC).
当您未为其提供 DateTime
来获取DST时,可能无法考虑DST的偏移量:)
It can't possibly take DST into consideration when you're not providing it a DateTime
to fetch the offset for :)
假设 someDate
是 DateTime
,您可以使用:
DateTimeOffset dto = new DateTimeOffset(someDate, tzi.GetUtcOffset(someDate));
或者只是 ConvertTimeToUtc
:
var utcDate = TimeZoneInfo.ConvertTimeToUtc(someDate, tzi);
请注意,如果您的本地时间由于夏令时而发生两次,则应该计算出要执行的操作过渡,或者根本不会发生。
Note that you should work out what you want to do if your local time occurs twice due to a DST transition, or doesn't occur at all.
这篇关于中欧是否有通用的TimeZoneInfo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!