问题描述
我有一种从用户输入创建UTC DateTime
的方法,使用其地理位置的GMT偏移量:
public static DateTime LocalToUtc
(int year,int month,int day,int hour,decimal gmtOffset){
//参数验证这里
var dateTime = new DateTime(年,月,日).AddHours(小时);
var dateTimeOffset =
new DateTimeOffset(dateTime,TimeSpan.FromHours(gmtOffset));
return dateTimeOffset.UtcDateTime;
}
问题是这个功能关闭了一个小时如果这是用户时区的夏令时。
所以当我的个人GMT偏移为-8时,由于夏令时,当前时区的偏移量为-7。 b
$ b
如何更改上述功能以记录夏令时?不要我以某种方式需要从GMT偏移量创建一些时区对象并获取其时区偏移?
没有办法在不知道实际时区的情况下执行此操作:几个时区具有相同的基准UTC偏移量,但具有不同的夏令时规则。例如,W。欧洲标准时间和 W。中非标准时间均具有+01:00的偏移量,但前者支持DST,而后者不支持。所以偏移量不足以决定是否应用DST ...
您的方法应该采用 TimeZoneInfo
参数,而不是 gmtOffset
。这样,您可以使用 TimeZoneInfo.ConvertTime
方法转换日期,它将自动将DST考虑在内。
I have a method that creates a UTC DateTime
from user input, using the GMT offset of their geographical position:
public static DateTime LocalToUtc
(int year, int month, int day, int hour, decimal gmtOffset) {
// argument validation here
var dateTime = new DateTime(year, month, day).AddHours(hour);
var dateTimeOffset =
new DateTimeOffset(dateTime, TimeSpan.FromHours(gmtOffset));
return dateTimeOffset.UtcDateTime;
}
The problem is that this function is off by an hour if it's daylight savings in the user's timezone.
So while my personal GMT offset is -8, the current timezone offset is -7 because of daylight savings.
How do I change the function above to account for daylight savings? Don't I somehow need to create some timezone object from the GMT offset and get its timezone offset?
There is no way to do it without knowing the actual time zone: several time zones have the same base UTC offset, but with different rules for daylight saving time. For instance, W. Europe Standard Time and W. Central Africa Standard Time both have an offset of +01:00, but the former supports DST while the latter doesn't. So the offset is not enough to decide whether DST applies or not...
Your method should take a TimeZoneInfo
parameter instead of gmtOffset
. This way you can just use the TimeZoneInfo.ConvertTime
method to convert the date, it will automatically take DST into account.
这篇关于.NET:计算夏令时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!