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

问题描述 投票:1回答:2

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

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

现在,如果偏移(x分钟)与保存在数据库中的偏移(和时区)不同,那么将向用户显示距离UTC x分钟的时区列表,以便他们可以从中选择一个。然后,选定的时区和相应的偏移量(x分钟)将作为用户的最新时区保存在数据库中。

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

例如,如果用户离UTC的距离是+330分钟,那么用户会得到以下提示:

我们发现你比格林威治标准时间提前了5小时。请选择您当前的时区:“Asia / Colombo”,“Asia / Kolkata”

c# datetime timezone nodatime
2个回答
2
投票

你可以这样做:

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

现在你有一个时区的集合!您可以根据您的具体情况将DateTime.Now替换为其他日期或DateTimeOffset

在Noda Time中,您可以这样做:

using NodaTime;
using NodaTime.TimeZones;

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

1
投票

使用目标偏移量而不是将每个偏移量转换为TimeSpan,使用“now”的单个计算(对于一致的结果)并使用IDateTimeZoneProvider.GetAllZones扩展方法,稍微替代Sweeper的代码。

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);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.