如何在 dot net core 的另一个时区获取本地时间

How do I get local time in another timezone in dot net core

我正在解决一个问题,我需要获取另一个时区的当前日期和时间。我不知道我的代码 运行 在哪个时区,它需要在 windows 和 linux 机器上工作。

我还没有找到任何方法。有什么想法吗?

(P.S:我特别需要找到瑞典的时间,包括任何任意时区的夏令时代码可能 运行ning in)。

瑞典的 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);

如果需要,您可以使用我的 TimeZoneConverter 库来简化此操作,它允许您在任何平台上使用任一 ID。

TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("Europe/Stockholm");
DateTimeOffset currentTimeInSweden = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, tzi);

如果在 .NET 6 或更新版本上 运行,并且您启用了 ICU globalization support,则您不再需要使用我的库。如果需要,.NET 将自动从一种格式转换为另一种格式。所以你可以这样做:

TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Europe/Stockholm");
DateTimeOffset currentTimeInSweden = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, tzi);

另请注意,代码 运行 所在的时区不相关,也不应该相关。 瑞典的夏令时规则是唯一相关的,而不是代码可能在运行中的时区的规则。

最后请注意,如果您希望获得有效结果,则必须正确设置计算机的时钟。始终使用 NTP 或 OS 的“自动设置日期和时间”功能将计算机时钟与 Internet 同步。