使用 Noda Time 以分钟为单位获取给定偏移量的时区列表

Get list of time zones for a given offset in minutes using Noda Time

我正在尝试使用 Noda Time 设计以下时区解决方案:

用户会使用移动应用程序或网络应用程序登录系统。在登录时,将使用与 UTC 的偏移量(假设 x 分钟)作为参数调用 Web API。

现在,如果偏移量(x 分钟)与保存在数据库中的偏移量(和时区)不同,那么用户将看到与 UTC 相差 x 分钟的时区列表,这样他们就可以 select 其中之一。 selected 时区和相应的偏移量(x 分钟)将作为用户的最新时区保存在数据库中。

如何使用 Noda Time 获取距 UTC x 分钟的时区列表?

例如,如果用户距 UTC +330 分钟,则用户会收到此提示:

We have found that you're 5 hrs 30 minutes ahead of GMT. Please select your current timezone: "Asia/Colombo", "Asia/Kolkata"

你可以这样做:

TimeZoneInfo.GetSystemTimeZones()
    .Where(x => x.GetUtcOffset(DateTime.Now).TotalMinutes == 330)

现在您有了时区集合!您可以根据您的情况用其他日期或 DateTimeOffset 替换 DateTime.Now

在野田时代,你可以这样做:

using NodaTime;
using NodaTime.TimeZones;

TzdbDateTimeZoneSource.Default.GetIds()
    .Select(x => TzdbDateTimeZoneSource.Default.ForId(x))
    .Where(x => 
        x.GetUtcOffset(SystemClock.Instance.GetCurrentInstant()).ToTimeSpan().TotalMinutes == 330)

Sweeper 代码的一种略微替代方法,使用目标偏移量而不是将每个偏移量转换为 TimeSpan,使用 "now" 的单个计算(以获得一致的结果)并使用 IDateTimeZoneProvider.GetAllZones扩展方法。

using System;
using System.Linq;
using NodaTime;
using NodaTime.Extensions;

class Test
{
    static void Main()
    {
        // No FromMinutes method for some reason...
        var target = Offset.FromSeconds(330 * 60);
        var now = SystemClock.Instance.GetCurrentInstant();
        var zones = DateTimeZoneProviders.Tzdb.GetAllZones()
            .Where(zone => zone.GetUtcOffset(now) == target);
        foreach (var zone in zones)
        {
            Console.WriteLine(zone.Id);
        }
    }
}