如何在 dot net core 的另一个时区获取当地时间 [英] How do I get local time in another timezone in dot net core

查看:41
本文介绍了如何在 dot net core 的另一个时区获取当地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决一个问题,我需要在另一个时区获取当前日期和时间.我不知道我的代码将在哪个时区运行,它需要在 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?

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

(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.欧洲标准时间".

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.

这篇关于如何在 dot net core 的另一个时区获取当地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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