使用NodaTime获取时区(字符串)的偏移分钟 [英] Get offset minutes from timezone (string) with NodaTime

查看:49
本文介绍了使用NodaTime获取时区(字符串)的偏移分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我只有代表时区的字符串,那么获取分钟的最简单方法是什么?(例如欧洲/伦敦")

What's the easiest way to get the minutes if I only have a string that represents the timezone? (for example "Europe/London")

到目前为止,我有:

public static int ConvertFromTimeZoneToMinutesOffset(string timeZone)
{
    DateTimeZone zone = DateTimeZoneProviders.Tzdb[timeZone];

    // Need magic code to get offset as minutes
}

但是我找不到将其转换为分钟的简单方法.

But I'm not finding an easy approach to convert it to minutes.

注意:我需要的是执行代码的特定时刻的偏移量.在该时区和UTC之间.

NOTE: What I need is the offset in that specific moment in which the code is being executed. Between that timezone and 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 ,但这会导致难以编写代码测试.

You could leave off the IClock parameter and instead use SystemClock.Instance in the method, but that leads to code which is harder to test.

这篇关于使用NodaTime获取时区(字符串)的偏移分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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