我在应用程序中使用 NodaTime,我需要用户从下拉列表中选择他们的时区。我有以下软要求:
1) 该列表仅包含对当前和不久的将来真实地点合理有效的选择。历史的、晦涩的和通用的时区应该被过滤掉。
2) 该列表应首先按 UTC 偏移量排序,然后按时区名称排序。这希望将它们按照对用户有意义的顺序排列。
我编写了以下代码,它确实有效,但并不完全符合我的要求。滤波器可能需要调整,我宁愿让偏移量代表基本(非 dst)偏移量,而不是当前偏移量。
建议?建议?
var now = Instant.FromDateTimeUtc(DateTime.UtcNow);
var tzdb = DateTimeZoneProviders.Tzdb;
var list = from id in tzdb.Ids
where id.Contains("/") && !id.StartsWith("etc", StringComparison.OrdinalIgnoreCase)
let tz = tzdb[id]
let offset = tz.GetOffsetFromUtc(now)
orderby offset, id
select new
{
Id = id,
DisplayValue = string.Format("({0}) {1}", offset.ToString("+HH:mm", null), id)
};
// ultimately we build a dropdown list, but for demo purposes you can just dump the results
foreach (var item in list)
Console.WriteLine(item.DisplayValue);
野田时间 1.1 有zone.tab 数据 http://noda-time.googlecode.com/hg-history/1.1.x/docs/api/html/T_NodaTime_TimeZones_TzdbZoneLocation.htm,因此您现在可以执行以下操作:
/// <summary>
/// Returns a list of valid timezones as a dictionary, where the key is
/// the timezone id, and the value can be used for display.
/// </summary>
/// <param name="countryCode">
/// The two-letter country code to get timezones for.
/// Returns all timezones if null or empty.
/// </param>
public IDictionary<string, string> GetTimeZones(string countryCode)
{
var now = SystemClock.Instance.Now;
var tzdb = DateTimeZoneProviders.Tzdb;
var list =
from location in TzdbDateTimeZoneSource.Default.ZoneLocations
where string.IsNullOrEmpty(countryCode) ||
location.CountryCode.Equals(countryCode,
StringComparison.OrdinalIgnoreCase)
let zoneId = location.ZoneId
let tz = tzdb[zoneId]
let offset = tz.GetZoneInterval(now).StandardOffset
orderby offset, zoneId
select new
{
Id = zoneId,
DisplayValue = string.Format("({0:+HH:mm}) {1}", offset, zoneId)
};
return list.ToDictionary(x => x.Id, x => x.DisplayValue);
}
替代方法
您可以使用基于地图的时区选择器 https://github.com/dosx/timezone-picker.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)