如何查找应用夏令时的时区和返回时间?
我正在尝试查找应用了夏令时的时区和返回时间?
目前我可以:
- 查找时区
- 获取 utc 偏移量
- 计算本地时间 确定
- 时区是否使用夏令时
- 获取夏令时的规则
- 确定当前时间是否使用夏令时
但是我在应用规则时遇到问题,这里是代码:
仅供参考
System.DateTime.Now.ToUniversalTime().Add(timeDiffUtcClient)
returns = 2010/07/10 09:25:45 AM
DateTime localDate = System.DateTime.Now.ToUniversalTime();
// Get the venue time zone info
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
TimeSpan timeDiffUtcClient = tz.BaseUtcOffset;
localDate = System.DateTime.Now.ToUniversalTime().Add(timeDiffUtcClient);
if (tz.SupportsDaylightSavingTime && tz.IsDaylightSavingTime(localDate))
{
localDate = localDate.Subtract(tz.GetAdjustmentRules().Single(r => localDate >= r.DateStart && localDate <= r.DateEnd).DaylightDelta);
}
DateTimeOffset utcDate = localDate.ToUniversalTime();
return localDate;
最终值 localDate 为 {2010/07/10 08:20:40 AM}
它 应该是 {2010/07/10 09:20:40 AM}
由于某种原因休息了 1 小时。
I'm trying to Find a timezone and return time with DaylightSavingTime applied?
Currenty I can:
- find the time zone
- get utc offset
- calculate the local time based on that
- determine if the time zone uses DaylightSavingTime
- get the rules for DaylightSavingTime
- determine if the current time uses DaylightSavingTime
However I'm having issues applying the rules, here's the code:
fyi
System.DateTime.Now.ToUniversalTime().Add(timeDiffUtcClient)
returns = 2010/07/10 09:25:45 AM
DateTime localDate = System.DateTime.Now.ToUniversalTime();
// Get the venue time zone info
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
TimeSpan timeDiffUtcClient = tz.BaseUtcOffset;
localDate = System.DateTime.Now.ToUniversalTime().Add(timeDiffUtcClient);
if (tz.SupportsDaylightSavingTime && tz.IsDaylightSavingTime(localDate))
{
localDate = localDate.Subtract(tz.GetAdjustmentRules().Single(r => localDate >= r.DateStart && localDate <= r.DateEnd).DaylightDelta);
}
DateTimeOffset utcDate = localDate.ToUniversalTime();
return localDate;
The final value localDate of is {2010/07/10 08:20:40 AM}
It should be {2010/07/10 09:20:40 AM}
It's 1 hour off for some reason.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好的,我修复了它:
要测试它,您可以这样做:
然后在最后的“列表”上快速观看,然后访问 worldtimeserver.com 并确认一些城市。
ok, I fixed it:
To test it you can do this:
then do a quickwatch on "list" at the end and go to worldtimeserver.com and confirm a few cities.
我在这里加入有点晚了,但我不确定为什么你要手动完成这一切。你的整个功能不能被替换为:
I'm jumping in a bit late here, but I'm not sure why you're doing this all manually. Could not your entire function be replaced by:
您想忽略夏令时。
You want to ignore daylight savings.
要正确转换 DateTime 与 TimeZone 和夏令时,请使用 TimeZoneInfo.ConvertTime 方法。
To correctly convert DateTime with TimeZone and Daylight Saving Time, use the TimeZoneInfo.ConvertTime method.