.NET:计算夏令时

编程入门 行业动态 更新时间:2024-10-26 04:28:45
本文介绍了.NET:计算夏令时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一种从用户输入创建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:计算夏令时

本文发布于:2023-10-28 08:21:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536077.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:夏令时   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!