How should I populate a list of IANA / Olson time zones from Noda Time?

前端 未结 2 1706
广开言路
广开言路 2020-11-28 08:34

I am using NodaTime in an application, and I need the user to select their timezone from a dropdown list. I have the following soft requirements:

1) The list only c

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 09:07

    Noda Time 1.1 has the zone.tab data, so you can now do the following:

    /// 
    /// Returns a list of valid timezones as a dictionary, where the key is
    /// the timezone id, and the value can be used for display.
    /// 
    /// 
    /// The two-letter country code to get timezones for.
    /// Returns all timezones if null or empty.
    /// 
    public IDictionary 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);
    }
    

    Alternative Approach

    Instead of providing a drop down at all, you can use a map-based timezone picker.

    enter image description here

提交回复
热议问题