如何在点网核心中获取其他时区的本地时间

我正在解决一个问题,我需要获取其他时区的当前日期和时间。我不知道我的代码将在哪个时区运行,并且它需要在Windows和Linux计算机上都可以工作。

我还没有发现任何方法。有什么想法吗?

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

iCMS 回答:如何在点网核心中获取其他时区的本地时间

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

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

本文链接:https://www.f2er.com/1991992.html

大家都在问