Convert NodaTime DateTimeZone into TimeZoneInfo

后端 未结 4 1992
天涯浪人
天涯浪人 2021-02-14 04:40

I\'m using NodaTime because of its nice support for zoneinfo data, however I have a case where I need to convert the DateTimeZone into TimeZoneInfo for

4条回答
  •  灰色年华
    2021-02-14 04:57

    I would avoid using reflection if possible. I wouldn't like to bet on your approach working with future versions :)

    Feel free to file a feature request for this functionality for future versions, but for the moment I'd build up your reverse dictionary in a more stable way:

    // Note: this version lets you work with any IDateTimeZoneSource, although as the only
    // other built-in source is BclDateTimeZoneSource, that may be less useful :)
    private static IDictionary LoadTimeZoneMap(IDateTimeZoneSource source)
    {
        var nodaToWindowsMap = new Dictionary();
        foreach (var bclZone in TimeZoneInfo.GetSystemTimeZones())
        {
            var nodaId = source.MapTimeZoneId(bclZone);
            if (nodaId != null)
            {
                nodaToWindowsMap[nodaId] = bclZone.Id;
            }
        }
        return nodaToWindowsMap;
    }
    

    Of course, this won't cover all the time zones in TZDB. In fact, it won't even give all the information we could give based on the CLDR information we use... CLDR gives multiple mappings for each Windows ID, and we only store the first one at the moment. We've been trying to work out how to expose more of that, but haven't managed yet. Thoughts welcome on the Noda Time mailing list :)

    Also note that just because there's a mapping between the BCL and TZDB zones doesn't mean they'll actually give the same results for everything - it's just the closest mapping available.

提交回复
热议问题