简体   繁体   English

DateTimeOffset 的 TimeZoneInfo 转换失败

[英]TimeZoneInfo conversion of DateTimeOffset fails

In trying to convert a DateTimeOffset between two time zones, I've successfully used TimeZoneInfo.ConvertTime() , but I found a case where the conversion doesn't work.在尝试在两个时区之间转换DateTimeOffset时,我成功地使用了TimeZoneInfo.ConvertTime() ,但我发现了转换不起作用的情况。 That is - conversion between UTC+11.00 and UTC+10:30 which has no effect.也就是说 - UTC+11.00UTC+10:30之间的转换无效。

Here is my completely vanilla source:这是我完全香草的来源:

public static DateTimeOffset ConvertToNewTimeZone(this DateTimeOffset dt, string newTz)
{
  var tzi = DeduceTimeZone(newTz); // converts out of proprietary format into std format
  var result = TimeZoneInfo.ConvertTime(dt, tzi);
  return result;
}

And here's a debug view of the values of my variables.这是我的变量值的调试视图。

调试视图

Notice how the result is still in UTC+11:00 .请注意结果如何仍在UTC+11:00中。 I expected the result to be in 10:30 .我预计结果会在10:30出现。 Can anyone explain why the conversion didn't happen?谁能解释为什么转换没有发生? I'm not aware of any adjustments that might apply.我不知道任何可能适用的调整。

Because of the daylight saving time (DST), you may know that January is summer in the southern hemisphere where Lord Howe Island is located, if you try to convert a different date in winter, the offset will be 10:30.由于夏令时 (DST),您可能知道 1 月在豪勋爵岛所在的南半球是夏季,如果您尝试在冬季转换为不同的日期,则偏移量将为 10:30。

var dt = new DateTime(2022, 7, 1);
TimeZoneInfo.ConvertTime(new DateTimeOffset(dt), tzi);
// 22/7/1 02:30:00 +10:30

TimeZoneInfo.GetUtcOffset 时区信息.GetUtcOffset

Time zone essentials 时区要点

In the end I narrowed it down when I noticed that the implementation of the TimeZoneInfo in Windows is different from that in Linux and MacOS.最后,当我注意到 Windows 中 TimeZoneInfo 的实现与 Linux 和 MacOS 中的不同时,我缩小了范围。 My tests were inadvertently comparing local time (debugging on windows) with a different set of time zones (where I was logging from a Docker container running on AKS on Azure, which was a Linux container).我的测试无意中将本地时间(在 Windows 上调试)与一组不同的时区进行了比较(我从 Docker 容器在 Azure 上运行的 AKS 上登录,这是一个 Linux 容器)。

In the end, it appears that my time zone conversion defaulted to UTC, because the System Timezone Database is empty.最后,似乎我的时区转换默认为 UTC,因为系统时区数据库是空的。 That is, TimeZoneInfo.GetSystemTimeZones().Count == 0 .TimeZoneInfo.GetSystemTimeZones().Count == 0

Not sure what to do about it, but at least I know now why my code was failing.不知道该怎么办,但至少我现在知道为什么我的代码失败了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM