使用 NodaTime 从时区(字符串)获取偏移分钟数
Get offset minutes from timezone (string) with NodaTime
如果我只有一个表示时区的字符串,获取分钟数的最简单方法是什么? (例如 "Europe/London")
到目前为止我有:
public static int ConvertFromTimeZoneToMinutesOffset(string timeZone)
{
DateTimeZone zone = DateTimeZoneProviders.Tzdb[timeZone];
// Need magic code to get offset as minutes
}
但我找不到将其转换为分钟的简单方法。
注意:我需要的是在执行代码的特定时刻的偏移量。在该时区和 UTC 之间。
对分钟使用 DatePart() 函数。
你需要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
,但这会导致代码更难测试。
如果我只有一个表示时区的字符串,获取分钟数的最简单方法是什么? (例如 "Europe/London")
到目前为止我有:
public static int ConvertFromTimeZoneToMinutesOffset(string timeZone)
{
DateTimeZone zone = DateTimeZoneProviders.Tzdb[timeZone];
// Need magic code to get offset as minutes
}
但我找不到将其转换为分钟的简单方法。
注意:我需要的是在执行代码的特定时刻的偏移量。在该时区和 UTC 之间。
对分钟使用 DatePart() 函数。
你需要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
,但这会导致代码更难测试。