c# - 使用 NodaTime 从时区(字符串)获取偏移分钟数

标签 c# .net nodatime

如果我只有一个表示时区的字符串,获取分钟数的最简单方法是什么? (例如“欧洲/伦敦”)

到目前为止我有:

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/

相关文章:

c# - 在一次往返中执行多个 SQL 命令

.net - 使用 CodeDomProvider 编译到内存时,程序集找不到引用的程序集

C# 正则表达式替换意外行为

c# - Azure 中的 Restful Web 服务 : Web Role or Worker Role?

nodatime - 如何获取用作时区初始化程序的tzdb中的字符串列表?

c# - 由于 C# 中的保护级别而无法访问

c# - 访问azure存储服务

c# - 使用NodaTime,如何将Instant转换为对应系统的ZonedDateTime?

c# - 找不到与方案 net.tcp 匹配的基址

nodatime - 如何获取nodatime中两个日期之间的天数