如果我只有一个表示时区的字符串,获取分钟数的最简单方法是什么? (例如“欧洲/伦敦”)
到目前为止我有:
public static int ConvertFromTimeZoneToMinutesOffset(string timeZone)
{
DateTimeZone zone = DateTimeZoneProviders.Tzdb[timeZone];
// Need magic code to get offset as minutes
}
但我找不到将其转换为分钟的简单方法。
注意:我需要的是执行代码的特定时刻的偏移量。在该时区和 UTC 之间。
最佳答案
你需要DateTimeZone.GetUtcOffset(Instant)
:
public static int ConvertFromTimeZoneToMinutesOffset(string timeZone, IClock clock)
{
DateTimeZone zone = DateTimeZoneProviders.Tzdb[timeZone];
Offset offset = zone.GetUtcOffset(clock.Now);
return offset.Milliseconds / NodaConstants.MillisecondsPerMinute;
}
您可以放弃IClock
参数,而是在方法中使用SystemClock.Instance
,但这会导致代码更难编写测试。
关于c# - 使用 NodaTime 从时区(字符串)获取偏移分钟数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40006629/