/// <summary> /// Gets the <see cref="DaylightSavingsRule" /> in effect at a particular <paramref name="moment" /> /// </summary> /// <param name="standardOffset"></param> /// <param name="moment"></param> /// <param name="mostRecentDaylightSavingsRule"></param> /// <returns></returns> private bool TryGetMostRecentDaylightSavingsRule(TimeSpan standardOffset, Moment moment, out DaylightSavingsRule mostRecentDaylightSavingsRule) { mostRecentDaylightSavingsRule = null; DateTime dateTimeOfMoment = moment.ToDateTime(); TimeSpan mostRecentOffsetAdjustment = TimeSpan.Zero; DaylightSavingsRule mostRecentDaylightSavingsRulePriorToYear; if (TryGetMostRecentDaylightSavingsRulePriorToYear(dateTimeOfMoment.Year, out mostRecentDaylightSavingsRulePriorToYear)) { mostRecentOffsetAdjustment = mostRecentDaylightSavingsRulePriorToYear.AdjustmentToStandardOffset; mostRecentDaylightSavingsRule = mostRecentDaylightSavingsRulePriorToYear; } DaylightSavingsRule mostRecentDaylightSavingsRuleDuringYear; if (TryGetMostRecentDaylightSavingsRuleDuringYear(standardOffset, mostRecentOffsetAdjustment, moment, out mostRecentDaylightSavingsRuleDuringYear)) { mostRecentDaylightSavingsRule = mostRecentDaylightSavingsRuleDuringYear; } if (null == mostRecentDaylightSavingsRule) { return(false); } return(true); }
private bool TryGetMostRecentDaylightSavingsRuleDuringYear(TimeSpan standardOffset, TimeSpan mostRecentAdjustmentToStandardOffset, Moment moment, out DaylightSavingsRule mostRecentDaylightSavingsRule) { mostRecentDaylightSavingsRule = null; DateTime dateTimeOfMoment = moment.ToDateTime(); // get the DaylightSavingsRules from the current year. IEnumerable <DaylightSavingsRule> currentYearDaylightSavingsRules = GetAllDaylightSavingsRulesEffectiveInYear(dateTimeOfMoment.Year); // Guard: current year has no rules if (!currentYearDaylightSavingsRules.Any()) { return(false); } var momentRulesDictionary = new Dictionary <Moment, DaylightSavingsRule>(); IEnumerable <DaylightSavingsRule> orderedCurrentYearRules = OrderRulesByDayOfYear(currentYearDaylightSavingsRules, dateTimeOfMoment.Year); // initialize offset to offset at end of previous year TimeSpan effectiveAdjustmentToStandardOffset = mostRecentAdjustmentToStandardOffset; // determine the Moment each DaylightSavingsRule occurs foreach (DaylightSavingsRule daylightSavingsRule in orderedCurrentYearRules) { Moment momentDaylightSavingsRuleOccurs = daylightSavingsRule.ToMoment(standardOffset, effectiveAdjustmentToStandardOffset, dateTimeOfMoment.Year); momentRulesDictionary.Add(momentDaylightSavingsRuleOccurs, daylightSavingsRule); // update daylight savings adjustment effectiveAdjustmentToStandardOffset = daylightSavingsRule.AdjustmentToStandardOffset; } // locate the most recent rule to have occured this year int i = 0; while (momentRulesDictionary.Count > i && momentRulesDictionary.ElementAt(i).Key < moment) { mostRecentDaylightSavingsRule = momentRulesDictionary.ElementAt(i).Value; i++; } return(true); }