mattjohnsonpint/TimeZoneConverter

Failed to detect timezone "Greenwich Mean Time" on mac visual studio 2022

akashbhujbalMentora opened this issue · 1 comments

when I try to detect the timezone using "TimeZoneConverter" Version - 6.1.0, on mac visual studio 2022 with using following code snippet -

var timeZoneName = TimeZoneInfo.Local;
currTimezoneId = TZConvert.WindowsToIana(timeZoneName.StandardName);

am getting this error - "Greenwich Mean Time" not recognized as valid windows time zone Id"
errorImage

Strange thing is that same code is working fine on the windows visual studio with same version.

Hi. There are two problems with the code you provided:

  • You're attempting to convert from Windows to IANA, but on a Mac the local time zone coming from the operating system will already be an IANA time zone.

  • You're using StandardName instead of Id. The standard name on Windows will sometimes match the time zone id, but only in English, and even then only for certain time zones. TimeZoneConverter is concerned only with IDs intended for computers, not with names intended for humans.

Indeed, the error message you show is appropriate for what is happening. The string "Greenwich Mean Time" is not a valid Windows time zone identifier.

If you are trying to get the IANA time zone ID with the same code on both Windows and MacOS, then you can do something like this instead:

static string GetIanaTimeZoneId(TimeZoneInfo tz) =>
    RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
        ? TZConvert.WindowsToIana(tz.Id)
        : tz.Id;

Of course, if you're on .NET 6 or later, and on a machine with ICU present (which is always true for MacOS and modern Windows), then you don't even need TimeZoneConverter. You can just use the built-in functions:

static string GetIanaTimeZoneId(TimeZoneInfo tz)
{
    if (tz.HasIanaId)
        return tz.Id;

    if (TimeZoneInfo.TryConvertWindowsIdToIanaId(tz.Id, out var ianaId))
        return ianaId;

    throw new InvalidTimeZoneException();
}