我正在尝试使用Noda Time设计以下时区解决方案:
用户将使用移动应用程序或web应用程序登录到系统。登录时,将使用UTC的偏移量(假设x分钟)作为参数调用web。
现在,如果偏移量(x分钟)与保存在数据库中的偏移量(和时区)不同,那么将向用户显示一个时区列表,这些时区距UTC有x分钟之遥,因此他们可以从中选择一个。然后将选定的时区和相应的偏移量(x分钟)保存在数据库中,作为用户的最新时区。
如何获得使用Noda Time距UTC x分钟的时区列表?
例如,如果用户距离UTC +330分钟,那么用户将得到以下提示:
我们发现你比格林尼治时间早了5小时30分钟。请选择当前时区:“亚洲/科伦坡”、“亚洲/加尔各答”
发布于 2018-09-01 07:27:59
你可以这样做:
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)发布于 2018-09-03 06:17:57
一种略为替代的代码方法,使用目标偏移量,而不是将每个偏移量转换为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);
}
}
}https://stackoverflow.com/questions/52125602
复制相似问题