Using Time Zone ID on .NET Core v3.1 under multi-platform


Summary

How do I specify the timezone ID in .NET Core v3.1?

In macOS v11.6, the Time Zone Database is within the /usr/share/zoneinfo directory.

$ file /usr/share/zoneinfo/Asia/Tokyo
/usr/share/zoneinfo/Asia/Tokyo: timezone data, version 2, 3 gmt time flags, 3 std time flags, no leap seconds, 8 transition times, 3 abbreviation chars

Therefore, when specifying the time zone id in Swift, do as follows. It’s the same for macOS and iOS.

let timezone = TimeZone(identifier: "Asia/Tokyo")

On the other hand, in .NET Core v3.1 (Windows), specify as follows.

System.TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");

If you use Tokyo Standard Time in macOS or iOS, it occurs System.TimeZoneNotFoundException. But Asia/Tokyo occurs the same exception on Windows.

Prerequisites

  • .NET Core v3.1
  • macOS v11.6
  • Windows 10 v21H1

Steps

Workaround 1: Branching with OS platform.

Example is here:

string timeZoneId = "Tokyo Standard Time"; // For Windows            
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) 
{
    // If you are using the code on Linux, consider branching with OSPlatform.Linux.
    timeZoneId = "Asia/Tokyo";
}

var utcTime = DateTime.UtcNow;
TimeZoneInfo jstTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
DateTime jstTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, jstTimeZone);

Console.WriteLine($"UTC - Date {utcTime}");
Console.WriteLine($"JST - Date {jstTime} TimeZoneId {timeZoneId}");

Workaround 2: Using the TimeZoneConverter package

See the info:

  • Cross-platform Time Zones with .NET Core – .NET Blog
  • References