Home > Blockchain >  TimeZoneInfo conversion of DateTimeOffset fails
TimeZoneInfo conversion of DateTimeOffset fails

Time:02-01

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. That is - conversion between UTC 11.00 and UTC 10:30 which has no effect.

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.

Debug View

Notice how the result is still in UTC 11:00. I expected the result to be in 10:30. Can anyone explain why the conversion didn't happen? I'm not aware of any adjustments that might apply.

CodePudding user response:

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.

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

TimeZoneInfo.GetUtcOffset

Time zone essentials

CodePudding user response:

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. 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).

In the end, it appears that my time zone conversion defaulted to UTC, because the System Timezone Database is empty. That is, TimeZoneInfo.GetSystemTimeZones().Count == 0.

Not sure what to do about it, but at least I know now why my code was failing.

  • Related