c# - 如何在 dot net core 中获取另一个时区的当地时间
问题描述
我正在解决一个问题,我需要在另一个时区获取当前日期和时间。我不知道我的代码将在哪个时区运行,它需要在 windows 和 linux 机器上运行。
我还没有找到任何方法来做到这一点。有任何想法吗?
(PS:我特别需要找出瑞典的时间,包括代码可能运行的任意时区的夏令时)。
解决方案
瑞典的 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);
另请注意,代码运行的时区不相关,也不应该相关。瑞典的夏令时规则是唯一相关的,而不是代码可能运行的时区的规则。
推荐阅读
- palantir-foundry - 是否可以通过 Foundry 数据连接将数据同步到数据集的特定分支?
- angular - TypeError:无法读取未定义的属性“subscribeTo”
- python - python:百分比格式在小数点后返回零
- python - 如何从另一个数据帧更新多索引数据帧?
- r - 使用 `data.table` 语法转换数据集
- matlab - 使用名称在 Matlab 循环中变化的矩阵加载 do 操作
- odata - 在 SAP UI5 `List` 中,“更多”按钮下方缺少“计数指标”[item-N / total-M]
- r - 将数据框转换为语料库时,如何将行标签保留在数据框中?
- powerbi - M 函数在 Power Query 编辑器中不起作用
- javascript - 找不到模块“打字稿”