FromLocation static method

TimeZoneRuleSet FromLocation(
  1. Location location, {
  2. int startYear = 1970,
})
Derives adjustment rules from the transitions of a [tz.Location], the way TimeZoneInfo.GetAdjustmentRules() describes a Windows time zone. Years with exactly one switch to and one switch back from daylight saving time become recurring rules (merged across consecutive years when they recur identically); any other offset change is kept exactly, as a rule starting at that moment. The location. The first year to describe; earlier years use the first rule.

Implementation

static TimeZoneRuleSet FromLocation(
  tz.Location location, {
  int startYear = 1970,
}) {
  // Collect the actual offset changes, bucketed by the local year in which they occur.
  final changesByYear = <int, List<_OffsetChange>>{};
  int lastChangeYear = startYear;
  for (int i = 0; i < location.transitionAt.length; i++) {
    final at = location.transitionAt[i];
    if (at <= _minInstant) {
      continue;
    }
    final previous = location.lookupTimeZone(at - 1).timeZone.offset;
    final next = location.zones[location.transitionZone[i]].offset;
    if (previous == next) {
      continue;
    }
    final change = _OffsetChange(at, previous, next);
    final year = change.WallBefore.year;
    if (year < startYear) {
      continue;
    }
    changesByYear.putIfAbsent(year, () => <_OffsetChange>[]).add(change);
    if (year > lastChangeYear) {
      lastChangeYear = year;
    }
  }

  final runs = <_Run>[];
  _Run? current;

  void startStandardRun(DateTime start, Duration offset) {
    current = _Run.standard(start, offset);
    runs.add(current!);
  }

  Duration offsetAt(DateTime utc) =>
      location.lookupTimeZone(utc.millisecondsSinceEpoch).timeZone.offset;

  // The timezone package database lists transitions up to 2037 only, after which
  // the last rules keep applying. When the changes stop earlier, the time zone
  // abolished them: describe one more year so the last rule ends.
  final int lastYear = lastChangeYear >= _LastDatabaseYear
      ? lastChangeYear
      : lastChangeYear + 1;

  for (int year = startYear; year <= lastYear; year++) {
    final yearStart = DateTime.utc(year);
    final changes = changesByYear[year] ?? const <_OffsetChange>[];

    if (changes.isEmpty) {
      final offset = offsetAt(DateTime.utc(year, 7, 1));
      if (current == null ||
          current!.SupportsDaylight ||
          current!.StandardOffset != offset) {
        startStandardRun(yearStart, offset);
      }
      continue;
    }

    final regular =
        changes.length == 2 &&
        changes[0].Before == changes[1].After &&
        changes[0].After == changes[1].Before;
    if (regular) {
      final daylightOffset = changes[0].Before > changes[0].After
          ? changes[0].Before
          : changes[0].After;
      final standardOffset = changes[0].Before > changes[0].After
          ? changes[0].After
          : changes[0].Before;
      final toDaylight = changes.firstWhere((c) => c.After == daylightOffset);
      final toStandard = changes.firstWhere((c) => c.After == standardOffset);
      final startCandidates = _Candidates(toDaylight.WallBefore);
      final endCandidates = _Candidates(toStandard.WallBefore);
      final delta = daylightOffset - standardOffset;

      if (current != null &&
          current!.SupportsDaylight &&
          current!.StandardOffset == standardOffset &&
          current!.DaylightDelta == delta) {
        final narrowedStart = current!.StartCandidates
            .where(startCandidates.contains)
            .toList();
        final narrowedEnd = current!.EndCandidates
            .where(endCandidates.contains)
            .toList();
        if (narrowedStart.isNotEmpty && narrowedEnd.isNotEmpty) {
          current!.StartCandidates = narrowedStart;
          current!.EndCandidates = narrowedEnd;
          continue;
        }
      }

      current = _Run(
        yearStart,
        standardOffset,
        delta,
        startCandidates,
        endCandidates,
      );
      runs.add(current!);
      continue;
    }

    // Irregular year: keep every offset change exactly.
    final initialOffset = changes.first.Before;
    if (current == null ||
        current!.SupportsDaylight ||
        current!.StandardOffset != initialOffset) {
      startStandardRun(yearStart, initialOffset);
    }
    for (final change in changes) {
      startStandardRun(change.WallAfter, change.After);
    }
  }

  if (runs.isEmpty) {
    return TimeZoneRuleSet(offsetAt(DateTime.now().toUtc()), []);
  }

  if (runs.length == 1 && !runs.single.SupportsDaylight) {
    return TimeZoneRuleSet(runs.single.StandardOffset, []);
  }

  final rules = <TimeZoneAdjustmentRule>[];
  for (int i = 0; i < runs.length; i++) {
    final run = runs[i];
    final start = i == 0 ? null : run.Start;
    final end = i + 1 < runs.length ? runs[i + 1].Start : null;
    rules.add(
      run.SupportsDaylight
          ? TimeZoneAdjustmentRule(
              start,
              end,
              run.StandardOffset,
              run.DaylightDelta,
              run.StartCandidates.first,
              run.EndCandidates.first,
            )
          : TimeZoneAdjustmentRule.Standard(start, end, run.StandardOffset),
    );
  }

  return TimeZoneRuleSet(runs.last.StandardOffset, rules);
}