如何在点网核心中获取其他时区的本地时间 [英] How do I get local time in another timezone in dot net core

查看:97
本文介绍了如何在点网核心中获取其他时区的本地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a problem in which I need to get the current date and time in another timezone. I don't know what timezone my code will be run on, and it needs to work on both windows and linux machines.

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

I have not found any way of doing this. Any ideas?

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

(P.S: I specifically need to find what time it is in Sweden including daylight savings from any arbitrary timezone the code might be running in).

推荐答案

瑞典的IANA时区ID为"Europe/Stockholm"(用于Linux,OSX和其他非Windows平台).瑞典的Windows时区ID为"W. Europe Standard Time".

The IANA time zone ID for Sweden is "Europe/Stockholm" (for use on Linux, OSX, and other non-Windows platforms). The Windows time zone ID for Sweden is "W. Europe Standard Time".

因此,您可以执行以下操作:

Thus, you can do the following:

// 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.

If desired, you can simplify this by using my TimeZoneConverter library, which allows you to use either id on any platform.

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

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

Also note that the time zone where the code is running is not relevant, nor should it be. The daylight savings rules of Sweden are the only that are relevant, not those of the time zone where the code might be running in.

这篇关于如何在点网核心中获取其他时区的本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆