首页 > 解决方案 > 如何在 dot net core 中获取另一个时区的当地时间

问题描述

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

我还没有找到任何方法来做到这一点。有任何想法吗?

(PS:我特别需要找出瑞典的时间,包括代码可能运行的任意时区的夏令时)。

标签: c#.net-coretimezonedatetimeoffset

解决方案


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

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


推荐阅读