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

折月煮酒 提交于 2020-07-10 08:12:41

问题


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?

(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).


回答1:


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);

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.



来源:https://stackoverflow.com/questions/62754305/how-do-i-get-local-time-in-another-timezone-in-dot-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!