Get offset minutes from timezone (string) with NodaTime

半世苍凉 提交于 2020-04-10 07:41:21

问题


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

So far I have:

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.

NOTE: What I need is the offset in that specific moment in which the code is being executed. Between that timezone and UTC.


回答1:


You need 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;
}

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.




回答2:


Use the DatePart() function on minutes.



来源:https://stackoverflow.com/questions/40006629/get-offset-minutes-from-timezone-string-with-nodatime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!