瑞典的 IANA 时区 ID 是"Europe/Stockholm"
(适用于 Linux、OSX 和其他非 Windows 平台)。瑞典的 Windows 时区 ID 是"W. Europe Standard Time"
.
因此,您可以执行以下操作:
// Determine the time zone ID for Sweden
string timeZoneId = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? "W. Europe Standard Time"
: "Europe/Stockholm";
// Get a TimeZoneInfo object for that time zone
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
// Convert the current UTC time to the time in Sweden
DateTimeOffset currentTimeInSweden = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, tzi);
如果需要,您可以使用我的来简化此操作时区转换器 https://github.com/mj1856/TimeZoneConverter库,它允许您在任何平台上使用任一 id。
TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("Europe/Stockholm");
DateTimeOffset currentTimeInSweden = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, tzi);
如果在 .NET 6 或更高版本上运行,并且您有ICU全球化支持 https://learn.microsoft.com/dotnet/core/extensions/globalization-icu启用后,您不再需要使用我的库。如果需要,.NET 将自动从一种格式转换为另一种格式。所以你可以这样做:
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Europe/Stockholm");
DateTimeOffset currentTimeInSweden = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, tzi);
另请注意,代码运行的时区不相关,也不应该相关。夏令时规则Sweden是唯一相关的,而不是代码可能运行所在的时区。
最后,请注意,如果您希望获得有效的结果,则必须正确设置计算机的时钟。请始终使用 NTP 或操作系统的“自动设置日期和时间”功能将计算机时钟与 Internet 同步。