Skip to main content

arrow_array/
timezone.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Timezone for timestamp arrays
6//!
7//! Without additional features, [`Tz`] only supports fixed offsets such as `+09:00`. The
8//! `chrono-tz` and `jiff` features add named timezones from the [IANA time zone database], such
9//! as `America/Los_Angeles`:
10//!
11//! * `chrono-tz` resolves names with [chrono-tz], which precomputes each zone's transitions up to
12//!   2099 and keeps the last offset for any later instant, so daylight saving no longer changes it.
13//! * `jiff` resolves names with [jiff], which applies each zone's daylight saving rules to any
14//!   instant, as `java.time` and libc do.
15//!
16//! When both are enabled, `jiff` is used. Cargo unifies features across a build, so enabling
17//! `jiff` for any crate changes how named timezones are resolved for every crate in the build.
18//!
19//! The `jiff` feature is experimental. It is a step in moving arrow-rs from chrono to jiff, so what
20//! it covers and how it behaves may change, even between minor releases.
21//!
22//! Each feature bundles its own copy of the database, which may be a different release, so the two
23//! can also disagree wherever the database changed between releases. [`tzdb_version`] returns the
24//! release in use.
25//!
26//! [IANA time zone database]: https://www.iana.org/time-zones
27//! [chrono-tz]: https://docs.rs/chrono-tz
28//! [jiff]: https://docs.rs/jiff
29
30use arrow_schema::ArrowError;
31use chrono::{DateTime, FixedOffset, NaiveDateTime};
32pub use private::{Tz, TzOffset};
33
34/// Returns the release of the [IANA time zone database] that resolves named timezones, such as
35/// `"2026c"`.
36///
37/// Returns `None` when neither the `chrono-tz` nor the `jiff` feature is enabled, as only fixed
38/// offsets are then supported.
39///
40/// [IANA time zone database]: https://www.iana.org/time-zones
41pub fn tzdb_version() -> Option<&'static str> {
42    #[cfg(feature = "jiff")]
43    {
44        Some(jiff_tzdb::VERSION)
45    }
46    #[cfg(all(feature = "chrono-tz", not(feature = "jiff")))]
47    {
48        Some(chrono_tz::IANA_TZDB_VERSION)
49    }
50    #[cfg(not(any(feature = "chrono-tz", feature = "jiff")))]
51    {
52        None
53    }
54}
55
56/// Parses a fixed offset of the form "+09:00", "-09" or "+0930"
57fn parse_fixed_offset(tz: &str) -> Option<FixedOffset> {
58    let bytes = tz.as_bytes();
59
60    let mut values = match bytes.len() {
61        // [+-]XX:XX
62        6 if bytes[3] == b':' => [bytes[1], bytes[2], bytes[4], bytes[5]],
63        // [+-]XXXX
64        5 => [bytes[1], bytes[2], bytes[3], bytes[4]],
65        // [+-]XX
66        3 => [bytes[1], bytes[2], b'0', b'0'],
67        _ => return None,
68    };
69    values.iter_mut().for_each(|x| *x = x.wrapping_sub(b'0'));
70    if values.iter().any(|x| *x > 9) {
71        return None;
72    }
73    let secs =
74        (values[0] * 10 + values[1]) as i32 * 60 * 60 + (values[2] * 10 + values[3]) as i32 * 60;
75
76    match bytes[0] {
77        b'+' => FixedOffset::east_opt(secs),
78        b'-' => FixedOffset::west_opt(secs),
79        _ => None,
80    }
81}
82
83#[cfg(feature = "jiff")]
84mod private {
85    use super::*;
86    use chrono::offset::TimeZone;
87    use chrono::{Datelike, LocalResult, NaiveDate, NaiveDateTime, NaiveTime, Offset, Timelike};
88    use jiff::Timestamp;
89    use jiff::civil::DateTime as JiffDateTime;
90    use jiff::tz::{AmbiguousOffset, TimeZone as JiffTimeZone};
91    use std::collections::HashMap;
92    use std::fmt::Display;
93    use std::str::FromStr;
94    use std::sync::OnceLock;
95
96    /// An [`Offset`] for [`Tz`]
97    #[derive(Debug, Copy, Clone)]
98    pub struct TzOffset {
99        tz: Tz,
100        offset: FixedOffset,
101    }
102
103    impl std::fmt::Display for TzOffset {
104        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105            self.offset.fmt(f)
106        }
107    }
108
109    impl Offset for TzOffset {
110        fn fix(&self) -> FixedOffset {
111            self.offset
112        }
113    }
114
115    /// A named timezone resolved by jiff, together with its name.
116    struct NamedTz {
117        name: &'static str,
118        tz: JiffTimeZone,
119    }
120
121    /// Prints only the name, so that `Debug` output matches the `chrono-tz` feature.
122    impl std::fmt::Debug for NamedTz {
123        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124            f.write_str(self.name)
125        }
126    }
127
128    /// Builds a timezone from jiff-tzdb. `jiff::tz::db()` would read the host's zoneinfo files
129    /// instead if any crate in the build enabled jiff's `tzdb-zoneinfo` feature.
130    fn bundled_tz(name: &str) -> Option<JiffTimeZone> {
131        // As jiff's own bundled database does, so that UTC is not backed by TZif data
132        if name == "UTC" {
133            return Some(JiffTimeZone::UTC);
134        }
135        let (canonical_name, tzif) = jiff_tzdb::get(name)?;
136        JiffTimeZone::tzif(canonical_name, tzif).ok()
137    }
138
139    /// Resolves a name in the bundled database. As with chrono-tz, and unlike jiff, names are case
140    /// sensitive.
141    ///
142    /// [`Tz`] is `Copy` but [`JiffTimeZone`] is reference counted, so `Tz` holds a `'static`
143    /// reference into a table with one slot per bundled name, each resolved on first use.
144    fn named_tz(name: &str) -> Result<&'static NamedTz, ArrowError> {
145        type Slots = HashMap<&'static str, OnceLock<Option<NamedTz>>, ahash::RandomState>;
146        static SLOTS: OnceLock<Slots> = OnceLock::new();
147        let slots = SLOTS.get_or_init(|| {
148            jiff_tzdb::available()
149                // A placeholder for an unknown local timezone, which chrono-tz does not accept
150                .filter(|name| *name != "Factory")
151                .map(|name| (name, OnceLock::new()))
152                .collect()
153        });
154        slots
155            .get_key_value(name)
156            .and_then(|(name, slot)| {
157                slot.get_or_init(|| {
158                    let tz = bundled_tz(name)?;
159                    Some(NamedTz { name, tz })
160                })
161                .as_ref()
162            })
163            // The same message as with chrono-tz
164            .ok_or_else(|| {
165                ArrowError::ParseError(format!(
166                    "Invalid timezone \"{name}\": failed to parse timezone"
167                ))
168            })
169    }
170
171    /// An Arrow [`TimeZone`]
172    #[derive(Debug, Copy, Clone)]
173    pub struct Tz(TzInner);
174
175    #[derive(Debug, Copy, Clone)]
176    enum TzInner {
177        Timezone(&'static NamedTz),
178        Offset(FixedOffset),
179    }
180
181    // These are copied per value by chrono, so catch any accidental growth
182    #[cfg(target_pointer_width = "64")]
183    const _: () = {
184        assert!(std::mem::size_of::<Tz>() == 16);
185        assert!(std::mem::size_of::<TzOffset>() == 24);
186    };
187
188    impl FromStr for Tz {
189        type Err = ArrowError;
190
191        fn from_str(tz: &str) -> Result<Self, Self::Err> {
192            match parse_fixed_offset(tz) {
193                Some(offset) => Ok(Self(TzInner::Offset(offset))),
194                None => Ok(Self(TzInner::Timezone(named_tz(tz)?))),
195            }
196        }
197    }
198
199    impl Display for Tz {
200        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201            match self.0 {
202                TzInner::Timezone(tz) => f.write_str(tz.name),
203                TzInner::Offset(offset) => offset.fmt(f),
204            }
205        }
206    }
207
208    fn fixed_offset(offset: jiff::tz::Offset) -> FixedOffset {
209        // The bundled database never holds an offset of a day or more, so this cannot fail
210        FixedOffset::east_opt(offset.seconds()).expect("timezone offset within a day")
211    }
212
213    /// The instant jiff should consult for a UTC datetime. jiff covers years -9999 to 9999;
214    /// anything outside that range takes the offset in force at the nearest covered instant.
215    fn jiff_timestamp(utc: &NaiveDateTime) -> Timestamp {
216        let seconds = utc.and_utc().timestamp();
217        Timestamp::from_second(seconds).unwrap_or(if seconds < 0 {
218            Timestamp::MIN
219        } else {
220            Timestamp::MAX
221        })
222    }
223
224    /// The civil datetime jiff should resolve for a local datetime, or `None` when the year is
225    /// outside jiff's range. Sub-second precision is irrelevant to the offset in force.
226    fn jiff_civil(local: &NaiveDateTime) -> Option<JiffDateTime> {
227        JiffDateTime::new(
228            i16::try_from(local.year()).ok()?,
229            local.month() as i8,
230            local.day() as i8,
231            local.hour() as i8,
232            local.minute() as i8,
233            local.second() as i8,
234            0,
235        )
236        .ok()
237    }
238
239    impl Tz {
240        fn offset(&self, offset: FixedOffset) -> TzOffset {
241            TzOffset { tz: *self, offset }
242        }
243    }
244
245    impl TimeZone for Tz {
246        type Offset = TzOffset;
247
248        fn from_offset(offset: &Self::Offset) -> Self {
249            offset.tz
250        }
251
252        fn offset_from_local_date(&self, local: &NaiveDate) -> LocalResult<Self::Offset> {
253            match self.0 {
254                TzInner::Offset(tz) => tz
255                    .offset_from_local_date(local)
256                    .map(|x| self.offset(x.fix())),
257                TzInner::Timezone(_) => {
258                    // As chrono-tz does, take an offset in force at the start or end of the day,
259                    // so that a day with a transition still resolves
260                    let earliest = self.offset_from_local_datetime(&local.and_time(NaiveTime::MIN));
261                    let latest =
262                        self.offset_from_local_datetime(&local.and_hms_opt(23, 59, 59).unwrap());
263                    match (earliest, latest) {
264                        (result @ LocalResult::Single(_), _) => result,
265                        (_, result @ LocalResult::Single(_)) => result,
266                        (LocalResult::Ambiguous(offset, _), _) => LocalResult::Single(offset),
267                        (_, LocalResult::Ambiguous(offset, _)) => LocalResult::Single(offset),
268                        (LocalResult::None, LocalResult::None) => LocalResult::None,
269                    }
270                }
271            }
272        }
273
274        fn offset_from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<Self::Offset> {
275            match self.0 {
276                TzInner::Offset(tz) => tz
277                    .offset_from_local_datetime(local)
278                    .map(|x| self.offset(x.fix())),
279                TzInner::Timezone(tz) => match jiff_civil(local) {
280                    // Outside jiff's range, treat the local datetime as if it were UTC. Either
281                    // way it takes the offset in force at the nearest covered instant.
282                    None => LocalResult::Single(self.offset_from_utc_datetime(local)),
283                    Some(dt) => match tz.tz.to_ambiguous_timestamp(dt).offset() {
284                        AmbiguousOffset::Unambiguous { offset } => {
285                            LocalResult::Single(self.offset(fixed_offset(offset)))
286                        }
287                        AmbiguousOffset::Gap { .. } => LocalResult::None,
288                        AmbiguousOffset::Fold { before, after } => LocalResult::Ambiguous(
289                            self.offset(fixed_offset(before)),
290                            self.offset(fixed_offset(after)),
291                        ),
292                    },
293                },
294            }
295        }
296
297        fn offset_from_utc_date(&self, utc: &NaiveDate) -> Self::Offset {
298            self.offset_from_utc_datetime(&utc.and_time(NaiveTime::MIN))
299        }
300
301        fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> Self::Offset {
302            match self.0 {
303                TzInner::Offset(tz) => self.offset(tz.offset_from_utc_datetime(utc).fix()),
304                TzInner::Timezone(tz) => {
305                    self.offset(fixed_offset(tz.tz.to_offset(jiff_timestamp(utc))))
306                }
307            }
308        }
309    }
310
311    pub(super) fn new_gap_info(local: &NaiveDateTime, tz: &Tz) -> Option<GapInfo> {
312        let TzInner::Timezone(named) = tz.0 else {
313            return None;
314        };
315        // A local datetime outside jiff's range resolves to a single offset, so it is not in a gap
316        let civil = jiff_civil(local)?;
317        let AmbiguousOffset::Gap { before, after } =
318            named.tz.to_ambiguous_timestamp(civil).offset()
319        else {
320            return None;
321        };
322        // Reading a local datetime in the gap with the later offset gives an instant before the
323        // transition, so the next transition is the one that opened the gap
324        let from = after.to_timestamp(civil).ok()?;
325        let transition = named.tz.following(from).next()?;
326        let end = DateTime::from_timestamp(transition.timestamp().as_second(), 0)?;
327        let begin = end.naive_utc() + chrono::TimeDelta::seconds(before.seconds().into());
328        Some(GapInfo {
329            begin: Some((begin, tz.offset(fixed_offset(before)))),
330            end: Some(end.with_timezone(tz)),
331        })
332    }
333
334    #[cfg(test)]
335    mod tests {
336        use super::*;
337        use chrono::{Timelike, Utc};
338
339        #[test]
340        fn test_with_timezone() {
341            let vals = [
342                Utc.timestamp_millis_opt(37800000).unwrap(),
343                Utc.timestamp_millis_opt(86339000).unwrap(),
344            ];
345
346            assert_eq!(10, vals[0].hour());
347            assert_eq!(23, vals[1].hour());
348
349            let tz: Tz = "America/Los_Angeles".parse().unwrap();
350
351            assert_eq!(2, vals[0].with_timezone(&tz).hour());
352            assert_eq!(15, vals[1].with_timezone(&tz).hour());
353        }
354
355        #[test]
356        fn test_dst_transitions_from_utc() {
357            let tz: Tz = "Australia/Sydney".parse().unwrap();
358            let standard = FixedOffset::east_opt(10 * 60 * 60).unwrap();
359            let daylight = FixedOffset::east_opt(11 * 60 * 60).unwrap();
360            let at = |y, m, d, h, min| {
361                NaiveDate::from_ymd_opt(y, m, d)
362                    .unwrap()
363                    .and_hms_opt(h, min, 0)
364                    .unwrap()
365            };
366            // Daylight time ended 2021-04-04T03:00+11:00, which is 2021-04-03T16:00Z
367            assert_eq!(
368                tz.offset_from_utc_datetime(&at(2021, 4, 3, 15, 30)).fix(),
369                daylight
370            );
371            assert_eq!(
372                tz.offset_from_utc_datetime(&at(2021, 4, 3, 16, 30)).fix(),
373                standard
374            );
375            // Daylight time started 2021-10-03T02:00+10:00, which is 2021-10-02T16:00Z
376            assert_eq!(
377                tz.offset_from_utc_datetime(&at(2021, 10, 2, 15, 30)).fix(),
378                standard
379            );
380            assert_eq!(
381                tz.offset_from_utc_datetime(&at(2021, 10, 2, 16, 30)).fix(),
382                daylight
383            );
384        }
385
386        #[test]
387        fn test_dst_transitions_from_local() {
388            let tz: Tz = "America/New_York".parse().unwrap();
389            let eastern_standard = FixedOffset::west_opt(5 * 60 * 60).unwrap();
390            let eastern_daylight = FixedOffset::west_opt(4 * 60 * 60).unwrap();
391            let at = |m, d, h, min| {
392                NaiveDate::from_ymd_opt(2024, m, d)
393                    .unwrap()
394                    .and_hms_opt(h, min, 0)
395                    .unwrap()
396            };
397            match tz.offset_from_local_datetime(&at(1, 15, 12, 0)) {
398                LocalResult::Single(offset) => assert_eq!(offset.fix(), eastern_standard),
399                other => panic!("expected a single offset, got {other:?}"),
400            }
401            // 02:30 on 2024-03-10 was skipped when clocks went forward
402            assert!(matches!(
403                tz.offset_from_local_datetime(&at(3, 10, 2, 30)),
404                LocalResult::None
405            ));
406            // 01:30 on 2024-11-03 happened twice; the daylight reading comes first
407            match tz.offset_from_local_datetime(&at(11, 3, 1, 30)) {
408                LocalResult::Ambiguous(first, second) => {
409                    assert_eq!(first.fix(), eastern_daylight);
410                    assert_eq!(second.fix(), eastern_standard);
411                }
412                other => panic!("expected an ambiguous offset, got {other:?}"),
413            }
414            // A date on a transition day still resolves to an offset in force that day
415            assert!(matches!(
416                tz.offset_from_local_date(&NaiveDate::from_ymd_opt(2024, 3, 10).unwrap()),
417                LocalResult::Single(_)
418            ));
419        }
420
421        /// chrono-tz keeps its last offset after 2099, while jiff keeps applying daylight saving
422        #[test]
423        fn test_dst_applies_after_2099() {
424            let hours = |h| FixedOffset::east_opt(h * 60 * 60).unwrap();
425            // Each zone's offsets in January and July
426            let zones = [
427                ("America/Los_Angeles", hours(-8), hours(-7)),
428                ("Australia/Sydney", hours(11), hours(10)),
429            ];
430            for (zone, january, july) in zones {
431                let tz: Tz = zone.parse().unwrap();
432                for year in [2024, 2100, 2300, 9999] {
433                    for (month, expected) in [(1, january), (7, july)] {
434                        let at = NaiveDate::from_ymd_opt(year, month, 1)
435                            .unwrap()
436                            .and_hms_opt(12, 0, 0)
437                            .unwrap();
438                        assert_eq!(
439                            tz.offset_from_utc_datetime(&at).fix(),
440                            expected,
441                            "{zone} {at}"
442                        );
443                        match tz.offset_from_local_datetime(&at) {
444                            LocalResult::Single(offset) => {
445                                assert_eq!(offset.fix(), expected, "local {zone} {at}")
446                            }
447                            other => panic!("expected a single offset for {at}, got {other:?}"),
448                        }
449                    }
450                }
451            }
452        }
453
454        /// chrono-tz has no transitions after 2099, so the comparison with it cannot check gaps
455        /// and folds there
456        #[test]
457        fn test_gaps_and_folds_after_2099() {
458            let tz: Tz = "America/Los_Angeles".parse().unwrap();
459            let pacific_standard = FixedOffset::west_opt(8 * 60 * 60).unwrap();
460            let pacific_daylight = FixedOffset::west_opt(7 * 60 * 60).unwrap();
461            let at = |y, m, d, h, min| {
462                NaiveDate::from_ymd_opt(y, m, d)
463                    .unwrap()
464                    .and_hms_opt(h, min, 0)
465                    .unwrap()
466            };
467            // The second Sunday in March and the first Sunday in November of each year
468            for (year, spring, fall) in [(2100, 14, 7), (2300, 11, 4), (9998, 8, 1)] {
469                let skipped = at(year, 3, spring, 2, 30);
470                assert!(matches!(
471                    tz.offset_from_local_datetime(&skipped),
472                    LocalResult::None
473                ));
474                let gap = GapInfo::new(&skipped, &tz).unwrap();
475                let (begin, begin_offset) = gap.begin.unwrap();
476                assert_eq!(begin, at(year, 3, spring, 2, 0));
477                assert_eq!(begin_offset.fix(), pacific_standard);
478                let end = gap.end.unwrap();
479                assert_eq!(end.naive_local(), at(year, 3, spring, 3, 0));
480                assert_eq!(end.offset().fix(), pacific_daylight);
481
482                match tz.offset_from_local_datetime(&at(year, 11, fall, 1, 30)) {
483                    LocalResult::Ambiguous(first, second) => {
484                        assert_eq!(first.fix(), pacific_daylight);
485                        assert_eq!(second.fix(), pacific_standard);
486                    }
487                    other => panic!("expected an ambiguous offset in {year}, got {other:?}"),
488                }
489            }
490        }
491
492        #[test]
493        fn test_beyond_jiff_range() {
494            let tz: Tz = "America/Los_Angeles".parse().unwrap();
495            let at = |year| {
496                NaiveDate::from_ymd_opt(year, 7, 1)
497                    .unwrap()
498                    .and_hms_opt(12, 0, 0)
499                    .unwrap()
500            };
501            // jiff covers years -9999 to 9999. Beyond that, rather than failing, the offset in
502            // force at the nearest covered instant applies: standard time at the end of 9999,
503            // and local mean time before the first transition.
504            let pacific_standard = FixedOffset::west_opt(8 * 60 * 60).unwrap();
505            let local_mean_time = FixedOffset::west_opt(7 * 60 * 60 + 52 * 60 + 58).unwrap();
506            for (year, expected) in [(20_000, pacific_standard), (-20_000, local_mean_time)] {
507                assert_eq!(
508                    tz.offset_from_utc_datetime(&at(year)).fix(),
509                    expected,
510                    "{year}"
511                );
512                match tz.offset_from_local_datetime(&at(year)) {
513                    LocalResult::Single(offset) => {
514                        assert_eq!(offset.fix(), expected, "local {year}")
515                    }
516                    other => panic!("expected a single offset for {year}, got {other:?}"),
517                }
518            }
519        }
520
521        #[test]
522        fn test_timezone_display() {
523            let test_cases = ["UTC", "America/Los_Angeles", "-08:00", "+05:30"];
524            for &case in &test_cases {
525                let tz: Tz = case.parse().unwrap();
526                assert_eq!(tz.to_string(), case);
527            }
528        }
529
530        #[test]
531        fn test_bundled_names() {
532            for name in jiff_tzdb::available() {
533                if name != "Factory" {
534                    let tz: Tz = name.parse().unwrap();
535                    assert_eq!(tz.to_string(), name);
536                }
537            }
538        }
539
540        #[test]
541        fn test_invalid_timezone() {
542            // jiff ignores case and knows some names that chrono-tz does not, but both features
543            // accept the same names
544            let names = [
545                "Not/AZone",
546                "america/los_angeles",
547                "utc",
548                "Etc/Unknown",
549                "Factory",
550            ];
551            for name in names {
552                let err = name.parse::<Tz>().unwrap_err().to_string();
553                let expected = format!("Invalid timezone \"{name}\"");
554                assert!(err.contains(&expected), "{err}");
555            }
556        }
557
558        #[test]
559        fn test_debug_matches_chrono_tz() {
560            let tz: Tz = "America/Los_Angeles".parse().unwrap();
561            assert_eq!(format!("{tz:?}"), "Tz(Timezone(America/Los_Angeles))");
562            let offset = tz.offset_from_utc_datetime(
563                &NaiveDate::from_ymd_opt(2024, 1, 1)
564                    .unwrap()
565                    .and_hms_opt(0, 0, 0)
566                    .unwrap(),
567            );
568            assert_eq!(
569                format!("{offset:?}"),
570                "TzOffset { tz: Tz(Timezone(America/Los_Angeles)), offset: -08:00 }"
571            );
572        }
573
574        /// With `--features chrono-tz,jiff` both engines are compiled, so these compare them
575        /// directly. They are expected to fail when either crate moves to a new release of the
576        /// IANA database, which is how such a change gets noticed.
577        #[cfg(feature = "chrono-tz")]
578        mod compare_with_chrono_tz {
579            use super::*;
580            use std::collections::BTreeSet;
581
582            /// Zones whose offsets differ only because the two engines bundle different releases.
583            /// When this test fails after a dependency update, review the differences and update
584            /// this list.
585            const KNOWN_DIFFERENCES: &[&str] = &[
586                "Africa/Casablanca",
587                "Africa/El_Aaiun",
588                "America/Araguaina",
589                "America/Bahia",
590                "America/Belem",
591                "America/Boa_Vista",
592                "America/Bogota",
593                "America/Campo_Grande",
594                "America/Cuiaba",
595                "America/Edmonton",
596                "America/Eirunepe",
597                "America/Ensenada",
598                "America/Fortaleza",
599                "America/Havana",
600                "America/Inuvik",
601                "America/Maceio",
602                "America/Manaus",
603                "America/Noronha",
604                "America/Porto_Acre",
605                "America/Porto_Velho",
606                "America/Rainy_River",
607                "America/Recife",
608                "America/Rio_Branco",
609                "America/Santa_Isabel",
610                "America/Santarem",
611                "America/Sao_Paulo",
612                "America/Tijuana",
613                "America/Vancouver",
614                "America/Winnipeg",
615                "America/Yellowknife",
616                "Asia/Tehran",
617                "Brazil/Acre",
618                "Brazil/DeNoronha",
619                "Brazil/East",
620                "Brazil/West",
621                "CST6CDT",
622                "Canada/Central",
623                "Canada/Mountain",
624                "Canada/Pacific",
625                "Cuba",
626                "EST5EDT",
627                "Eire",
628                "Europe/Chisinau",
629                "Europe/Dublin",
630                "Europe/Tiraspol",
631                "Iran",
632                "MST7MDT",
633                "Mexico/BajaNorte",
634                "PST8PDT",
635            ];
636
637            fn releases() -> String {
638                format!(
639                    "chrono-tz has tzdb {}, jiff-tzdb has tzdb {}",
640                    chrono_tz::IANA_TZDB_VERSION,
641                    jiff_tzdb::VERSION
642                )
643            }
644
645            fn at(seconds: i64) -> NaiveDateTime {
646                DateTime::from_timestamp(seconds, 0).unwrap().naive_utc()
647            }
648
649            /// The parts of a gap that both engines report: where it begins and ends
650            type Gap = (Option<(NaiveDateTime, FixedOffset)>, Option<NaiveDateTime>);
651
652            fn chrono_tz_gap(tz: &chrono_tz::Tz, local: &NaiveDateTime) -> Option<Gap> {
653                chrono_tz::GapInfo::new(local, tz).map(|gap| {
654                    (
655                        gap.begin.map(|(begin, offset)| (begin, offset.fix())),
656                        gap.end.map(|end| end.naive_utc()),
657                    )
658                })
659            }
660
661            fn jiff_gap(tz: &Tz, local: &NaiveDateTime) -> Option<Gap> {
662                GapInfo::new(local, tz).map(|gap| {
663                    (
664                        gap.begin.map(|(begin, offset)| (begin, offset.fix())),
665                        gap.end.map(|end| end.naive_utc()),
666                    )
667                })
668            }
669
670            /// Whether the engines agree when `datetime` is read as UTC and as local time
671            fn agree(chrono_tz: chrono_tz::Tz, jiff: Tz, datetime: &NaiveDateTime) -> bool {
672                chrono_tz_gap(&chrono_tz, datetime) == jiff_gap(&jiff, datetime)
673                    && chrono_tz.offset_from_utc_datetime(datetime).fix()
674                        == jiff.offset_from_utc_datetime(datetime).fix()
675                    && chrono_tz
676                        .offset_from_local_datetime(datetime)
677                        .map(|o| o.fix())
678                        == jiff.offset_from_local_datetime(datetime).map(|o| o.fix())
679            }
680
681            #[test]
682            fn test_same_names() {
683                let chrono: BTreeSet<_> =
684                    chrono_tz::TZ_VARIANTS.iter().map(|tz| tz.name()).collect();
685                let jiff: BTreeSet<_> = jiff_tzdb::available()
686                    .filter(|name| *name != "Factory")
687                    .collect();
688                assert_eq!(chrono, jiff, "{}", releases());
689            }
690
691            #[test]
692            fn test_same_offsets() {
693                // 1900-01-01 to 2099-01-01, before chrono-tz stops applying daylight saving
694                const START: i64 = -2_208_988_800;
695                const END: i64 = 4_070_908_800;
696                const WEEK: usize = 7 * 24 * 60 * 60;
697
698                let mut different = BTreeSet::new();
699                for variant in chrono_tz::TZ_VARIANTS {
700                    let name = variant.name();
701                    let jiff: Tz = name.parse().unwrap();
702                    let TzInner::Timezone(named) = jiff.0 else {
703                        unreachable!("{name} is not an offset");
704                    };
705
706                    // Weekly samples find transitions that only one engine knows about
707                    let mut samples: Vec<_> = (START..END).step_by(WEEK).map(at).collect();
708
709                    // Probing each side of every transition covers gaps and folds
710                    let start = Timestamp::from_second(START).unwrap();
711                    let transitions = named.tz.following(start);
712                    for t in transitions.take_while(|t| t.timestamp().as_second() < END) {
713                        let instant = t.timestamp().as_second();
714                        let after = i64::from(t.offset().seconds());
715                        let before = i64::from(
716                            named
717                                .tz
718                                .to_offset(Timestamp::from_second(instant - 1).unwrap())
719                                .seconds(),
720                        );
721                        samples.extend(
722                            [
723                                instant - 1,
724                                instant,
725                                instant + before - 1,
726                                instant + before,
727                                instant + after - 1,
728                                instant + after,
729                            ]
730                            .map(at),
731                        );
732                    }
733
734                    // Years in which the two releases give different UTC offsets
735                    let changed: BTreeSet<_> = samples
736                        .iter()
737                        .filter(|dt| {
738                            variant.offset_from_utc_datetime(dt).fix()
739                                != jiff.offset_from_utc_datetime(dt).fix()
740                        })
741                        .map(|dt| dt.year())
742                        .collect();
743                    if !changed.is_empty() {
744                        different.insert(name);
745                    }
746
747                    // Every other year must also agree on local times and gaps. Neighbouring
748                    // years are skipped too, as a local reading can fall in them.
749                    for dt in &samples {
750                        if !(dt.year() - 1..=dt.year() + 1).any(|y| changed.contains(&y)) {
751                            assert!(agree(variant, jiff, dt), "{name} at {dt}, {}", releases());
752                        }
753                    }
754                }
755                let known = KNOWN_DIFFERENCES.iter().copied().collect();
756                assert_eq!(different, known, "{}", releases());
757            }
758        }
759    }
760}
761
762#[cfg(all(feature = "chrono-tz", not(feature = "jiff")))]
763mod private {
764    use super::*;
765    use chrono::offset::TimeZone;
766    use chrono::{LocalResult, NaiveDate, NaiveDateTime, Offset};
767    use std::fmt::Display;
768    use std::str::FromStr;
769
770    /// An [`Offset`] for [`Tz`]
771    #[derive(Debug, Copy, Clone)]
772    pub struct TzOffset {
773        tz: Tz,
774        offset: FixedOffset,
775    }
776
777    impl std::fmt::Display for TzOffset {
778        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
779            self.offset.fmt(f)
780        }
781    }
782
783    impl Offset for TzOffset {
784        fn fix(&self) -> FixedOffset {
785            self.offset
786        }
787    }
788
789    /// An Arrow [`TimeZone`]
790    #[derive(Debug, Copy, Clone)]
791    pub struct Tz(TzInner);
792
793    #[derive(Debug, Copy, Clone)]
794    enum TzInner {
795        Timezone(chrono_tz::Tz),
796        Offset(FixedOffset),
797    }
798
799    impl FromStr for Tz {
800        type Err = ArrowError;
801
802        fn from_str(tz: &str) -> Result<Self, Self::Err> {
803            match parse_fixed_offset(tz) {
804                Some(offset) => Ok(Self(TzInner::Offset(offset))),
805                None => Ok(Self(TzInner::Timezone(tz.parse().map_err(|e| {
806                    ArrowError::ParseError(format!("Invalid timezone \"{tz}\": {e}"))
807                })?))),
808            }
809        }
810    }
811
812    impl Display for Tz {
813        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
814            match self.0 {
815                TzInner::Timezone(tz) => tz.fmt(f),
816                TzInner::Offset(offset) => offset.fmt(f),
817            }
818        }
819    }
820
821    macro_rules! tz {
822        ($s:ident, $tz:ident, $b:block) => {
823            match $s.0 {
824                TzInner::Timezone($tz) => $b,
825                TzInner::Offset($tz) => $b,
826            }
827        };
828    }
829
830    impl TimeZone for Tz {
831        type Offset = TzOffset;
832
833        fn from_offset(offset: &Self::Offset) -> Self {
834            offset.tz
835        }
836
837        fn offset_from_local_date(&self, local: &NaiveDate) -> LocalResult<Self::Offset> {
838            tz!(self, tz, {
839                tz.offset_from_local_date(local).map(|x| TzOffset {
840                    tz: *self,
841                    offset: x.fix(),
842                })
843            })
844        }
845
846        fn offset_from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<Self::Offset> {
847            tz!(self, tz, {
848                tz.offset_from_local_datetime(local).map(|x| TzOffset {
849                    tz: *self,
850                    offset: x.fix(),
851                })
852            })
853        }
854
855        fn offset_from_utc_date(&self, utc: &NaiveDate) -> Self::Offset {
856            tz!(self, tz, {
857                TzOffset {
858                    tz: *self,
859                    offset: tz.offset_from_utc_date(utc).fix(),
860                }
861            })
862        }
863
864        fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> Self::Offset {
865            tz!(self, tz, {
866                TzOffset {
867                    tz: *self,
868                    offset: tz.offset_from_utc_datetime(utc).fix(),
869                }
870            })
871        }
872    }
873
874    #[inline]
875    pub(super) fn new_gap_info(local: &NaiveDateTime, tz: &Tz) -> Option<GapInfo> {
876        let TzInner::Timezone(ctz) = &tz.0 else {
877            return None;
878        };
879        chrono_tz::GapInfo::new(local, ctz).map(|gi| GapInfo {
880            begin: gi.begin.map(|(ndt, ctz)| {
881                (
882                    ndt,
883                    TzOffset {
884                        tz: *tz,
885                        offset: ctz.fix(),
886                    },
887                )
888            }),
889            end: gi.end.map(|dt| dt.with_timezone(tz)),
890        })
891    }
892
893    #[cfg(test)]
894    mod tests {
895        use super::*;
896        use chrono::{Timelike, Utc};
897
898        #[test]
899        fn test_with_timezone() {
900            let vals = [
901                Utc.timestamp_millis_opt(37800000).unwrap(),
902                Utc.timestamp_millis_opt(86339000).unwrap(),
903            ];
904
905            assert_eq!(10, vals[0].hour());
906            assert_eq!(23, vals[1].hour());
907
908            let tz: Tz = "America/Los_Angeles".parse().unwrap();
909
910            assert_eq!(2, vals[0].with_timezone(&tz).hour());
911            assert_eq!(15, vals[1].with_timezone(&tz).hour());
912        }
913
914        #[test]
915        fn test_using_chrono_tz_and_utc_naive_date_time() {
916            let sydney_tz = "Australia/Sydney".to_string();
917            let tz: Tz = sydney_tz.parse().unwrap();
918            let sydney_offset_without_dst = FixedOffset::east_opt(10 * 60 * 60).unwrap();
919            let sydney_offset_with_dst = FixedOffset::east_opt(11 * 60 * 60).unwrap();
920            // Daylight savings ends
921            // When local daylight time was about to reach
922            // Sunday, 4 April 2021, 3:00:00 am clocks were turned backward 1 hour to
923            // Sunday, 4 April 2021, 2:00:00 am local standard time instead.
924
925            // Daylight savings starts
926            // When local standard time was about to reach
927            // Sunday, 3 October 2021, 2:00:00 am clocks were turned forward 1 hour to
928            // Sunday, 3 October 2021, 3:00:00 am local daylight time instead.
929
930            // Sydney 2021-04-04T02:30:00+11:00 is 2021-04-03T15:30:00Z
931            let utc_just_before_sydney_dst_ends = NaiveDate::from_ymd_opt(2021, 4, 3)
932                .unwrap()
933                .and_hms_nano_opt(15, 30, 0, 0)
934                .unwrap();
935            assert_eq!(
936                tz.offset_from_utc_datetime(&utc_just_before_sydney_dst_ends)
937                    .fix(),
938                sydney_offset_with_dst
939            );
940            // Sydney 2021-04-04T02:30:00+10:00 is 2021-04-03T16:30:00Z
941            let utc_just_after_sydney_dst_ends = NaiveDate::from_ymd_opt(2021, 4, 3)
942                .unwrap()
943                .and_hms_nano_opt(16, 30, 0, 0)
944                .unwrap();
945            assert_eq!(
946                tz.offset_from_utc_datetime(&utc_just_after_sydney_dst_ends)
947                    .fix(),
948                sydney_offset_without_dst
949            );
950            // Sydney 2021-10-03T01:30:00+10:00 is 2021-10-02T15:30:00Z
951            let utc_just_before_sydney_dst_starts = NaiveDate::from_ymd_opt(2021, 10, 2)
952                .unwrap()
953                .and_hms_nano_opt(15, 30, 0, 0)
954                .unwrap();
955            assert_eq!(
956                tz.offset_from_utc_datetime(&utc_just_before_sydney_dst_starts)
957                    .fix(),
958                sydney_offset_without_dst
959            );
960            // Sydney 2021-04-04T03:30:00+11:00 is 2021-10-02T16:30:00Z
961            let utc_just_after_sydney_dst_starts = NaiveDate::from_ymd_opt(2022, 10, 2)
962                .unwrap()
963                .and_hms_nano_opt(16, 30, 0, 0)
964                .unwrap();
965            assert_eq!(
966                tz.offset_from_utc_datetime(&utc_just_after_sydney_dst_starts)
967                    .fix(),
968                sydney_offset_with_dst
969            );
970        }
971
972        #[test]
973        fn test_timezone_display() {
974            let test_cases = ["UTC", "America/Los_Angeles", "-08:00", "+05:30"];
975            for &case in &test_cases {
976                let tz: Tz = case.parse().unwrap();
977                assert_eq!(tz.to_string(), case);
978            }
979        }
980    }
981}
982
983#[cfg(not(any(feature = "chrono-tz", feature = "jiff")))]
984mod private {
985    use super::*;
986    use chrono::offset::TimeZone;
987    use chrono::{LocalResult, NaiveDate, NaiveDateTime, Offset};
988    use std::str::FromStr;
989
990    /// An [`Offset`] for [`Tz`]
991    #[derive(Debug, Copy, Clone)]
992    pub struct TzOffset(FixedOffset);
993
994    impl std::fmt::Display for TzOffset {
995        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
996            self.0.fmt(f)
997        }
998    }
999
1000    impl Offset for TzOffset {
1001        fn fix(&self) -> FixedOffset {
1002            self.0
1003        }
1004    }
1005
1006    /// An Arrow [`TimeZone`]
1007    #[derive(Debug, Copy, Clone)]
1008    pub struct Tz(FixedOffset);
1009
1010    impl FromStr for Tz {
1011        type Err = ArrowError;
1012
1013        fn from_str(tz: &str) -> Result<Self, Self::Err> {
1014            let offset = parse_fixed_offset(tz).ok_or_else(|| {
1015                ArrowError::ParseError(format!(
1016                    "Invalid timezone \"{tz}\": only offset based timezones supported without chrono-tz or jiff feature"
1017                ))
1018            })?;
1019            Ok(Self(offset))
1020        }
1021    }
1022
1023    impl TimeZone for Tz {
1024        type Offset = TzOffset;
1025
1026        fn from_offset(offset: &Self::Offset) -> Self {
1027            Self(offset.0)
1028        }
1029
1030        fn offset_from_local_date(&self, local: &NaiveDate) -> LocalResult<Self::Offset> {
1031            self.0.offset_from_local_date(local).map(TzOffset)
1032        }
1033
1034        fn offset_from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<Self::Offset> {
1035            self.0.offset_from_local_datetime(local).map(TzOffset)
1036        }
1037
1038        fn offset_from_utc_date(&self, utc: &NaiveDate) -> Self::Offset {
1039            TzOffset(self.0.offset_from_utc_date(utc).fix())
1040        }
1041
1042        fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> Self::Offset {
1043            TzOffset(self.0.offset_from_utc_datetime(utc).fix())
1044        }
1045    }
1046
1047    #[inline]
1048    pub(super) fn new_gap_info(_local: &NaiveDateTime, _tz: &Tz) -> Option<GapInfo> {
1049        // Fixed offsets never contain gaps
1050        None
1051    }
1052}
1053
1054/// Represents the information of a gap.
1055///
1056/// This returns useful information that can be used when converting a local [`NaiveDateTime`]
1057/// to a timezone-aware [`DateTime`] with [`chrono::TimeZone::from_local_datetime`] and a gap
1058/// ([`chrono::LocalResult::None`]) is found.
1059///
1060/// # Examples
1061///
1062/// In the `America/New_York` timezone the clocks went forward one hour at `2026-03-08T02:00:00`.
1063/// The local time `2026-03-08T01:30:00` exists, but `2026-03-08T02:30:00` falls in the gap and
1064/// does not.
1065///
1066/// ```
1067/// # #[cfg(any(feature = "chrono-tz", feature = "jiff"))]
1068/// # {
1069/// use arrow_array::timezone::{GapInfo, Tz};
1070/// use chrono::{DateTime, FixedOffset, LocalResult, NaiveDateTime, Offset, TimeZone};
1071///
1072/// let tz: Tz = "America/New_York".parse().unwrap();
1073/// let expect_offset: FixedOffset = "-0500".parse().unwrap();
1074///
1075/// // A local time before the gap has a single offset, and is not in a gap.
1076/// let exists: NaiveDateTime = "2026-03-08T01:30:00".parse().unwrap();
1077/// let offset = tz.offset_from_local_datetime(&exists).single().unwrap();
1078/// assert_eq!(offset.fix(), expect_offset);
1079/// assert!(GapInfo::new(&exists, &tz).is_none());
1080///
1081/// // A local time inside the gap has no offset...
1082/// let not_exist: NaiveDateTime = "2026-03-08T02:30:00".parse().unwrap();
1083/// let offset = tz.offset_from_local_datetime(&not_exist);
1084/// assert!(matches!(offset, LocalResult::None));
1085///
1086/// // ...but `GapInfo` describes the gap it falls in.
1087/// let GapInfo { begin, end } = GapInfo::new(&not_exist, &tz).unwrap();
1088///
1089/// // The gap begins at 02:00 local time. The offset is the one in effect before the gap.
1090/// let (begin_datetime, begin_offset) = begin.unwrap();
1091/// let expect_begin: NaiveDateTime = "2026-03-08T02:00:00".parse().unwrap();
1092/// assert_eq!(begin_datetime, expect_begin);
1093/// assert_eq!(begin_offset.fix(), expect_offset);
1094///
1095/// // The gap ends at 03:00 local time, with the offset in effect after the gap.
1096/// let expect_end: DateTime<FixedOffset> = "2026-03-08T03:00:00-0400".parse().unwrap();
1097/// assert_eq!(end.unwrap(), expect_end.with_timezone(&tz));
1098/// # }
1099/// ```
1100#[derive(Debug, Clone, Copy)]
1101pub struct GapInfo {
1102    /// When available it contains information about the beginning of the gap.
1103    ///
1104    /// The time represents the first instant in which the gap starts.
1105    /// This means that it is the first instant that when used with
1106    /// [`chrono::TimeZone::from_local_datetime`] it will return
1107    /// [`chrono::LocalResult::None`].
1108    ///
1109    /// The offset represents the offset of the first instant before the gap.
1110    pub begin: Option<(NaiveDateTime, TzOffset)>,
1111
1112    /// When available it contains the first instant after the gap.
1113    pub end: Option<DateTime<Tz>>,
1114}
1115
1116impl GapInfo {
1117    /// Return information about a gap.
1118    ///
1119    /// It returns `None` if `local` is not in a gap for the current timezone. Timezones
1120    /// that represent fixed offsets contain no gaps and therefore always return `None`.
1121    ///
1122    /// If `local` is at the limits of the known timestamps the fields `begin` or `end` in
1123    /// [`GapInfo`] will be `None`.
1124    pub fn new(local: &NaiveDateTime, tz: &Tz) -> Option<Self> {
1125        private::new_gap_info(local, tz)
1126    }
1127}
1128
1129#[cfg(test)]
1130mod tests {
1131    use super::*;
1132    use chrono::{NaiveDate, Offset, TimeZone};
1133    use rstest::rstest;
1134
1135    #[test]
1136    fn test_with_offset() {
1137        let t = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
1138
1139        let tz: Tz = "-00:00".parse().unwrap();
1140        assert_eq!(tz.offset_from_utc_date(&t).fix().local_minus_utc(), 0);
1141        let tz: Tz = "+00:00".parse().unwrap();
1142        assert_eq!(tz.offset_from_utc_date(&t).fix().local_minus_utc(), 0);
1143
1144        let tz: Tz = "-10:00".parse().unwrap();
1145        assert_eq!(
1146            tz.offset_from_utc_date(&t).fix().local_minus_utc(),
1147            -10 * 60 * 60
1148        );
1149        let tz: Tz = "+09:00".parse().unwrap();
1150        assert_eq!(
1151            tz.offset_from_utc_date(&t).fix().local_minus_utc(),
1152            9 * 60 * 60
1153        );
1154
1155        let tz = "+09".parse::<Tz>().unwrap();
1156        assert_eq!(
1157            tz.offset_from_utc_date(&t).fix().local_minus_utc(),
1158            9 * 60 * 60
1159        );
1160
1161        let tz = "+0900".parse::<Tz>().unwrap();
1162        assert_eq!(
1163            tz.offset_from_utc_date(&t).fix().local_minus_utc(),
1164            9 * 60 * 60
1165        );
1166
1167        let err = "+9:00".parse::<Tz>().unwrap_err().to_string();
1168        assert!(err.contains("Invalid timezone"), "{}", err);
1169    }
1170
1171    #[rstest]
1172    #[case::ordinary_time(
1173        NaiveDate::from_ymd_opt(2000, 1, 1)
1174            .unwrap()
1175            .and_hms_opt(0, 0, 0)
1176            .unwrap()
1177    )]
1178    // These readings fall in DST gaps in some named zones, but not in fixed offsets.
1179    #[case::us_dst_gap_time(
1180        NaiveDate::from_ymd_opt(2021, 3, 14)
1181            .unwrap()
1182            .and_hms_opt(2, 30, 0)
1183            .unwrap()
1184    )]
1185    #[case::european_dst_gap_time(
1186        NaiveDate::from_ymd_opt(2021, 3, 28)
1187            .unwrap()
1188            .and_hms_opt(1, 30, 0)
1189            .unwrap()
1190    )]
1191    fn test_gap_info_fixed_offset(
1192        #[case] time: NaiveDateTime,
1193        #[values("+00:00", "-05:00", "+01:00", "+09:30")] tz: &str,
1194    ) {
1195        let tz: Tz = tz.parse().unwrap();
1196        assert!(GapInfo::new(&time, &tz).is_none(), "{tz:?} {time}");
1197    }
1198
1199    #[cfg(any(feature = "chrono-tz", feature = "jiff"))]
1200    mod gap_info {
1201        use super::*;
1202        use chrono::Utc;
1203
1204        fn naive(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> NaiveDateTime {
1205            NaiveDate::from_ymd_opt(y, mo, d)
1206                .unwrap()
1207                .and_hms_opt(h, mi, 0)
1208                .unwrap()
1209        }
1210
1211        fn utc(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> chrono::DateTime<Utc> {
1212            Utc.with_ymd_and_hms(y, mo, d, h, mi, 0).unwrap()
1213        }
1214
1215        #[test]
1216        fn test_gap_info_not_in_gap() {
1217            let tz: Tz = "America/New_York".parse().unwrap();
1218            // Just before and at the end of the 2021 spring forward gap
1219            assert!(GapInfo::new(&naive(2021, 3, 14, 1, 59), &tz).is_none());
1220            assert!(GapInfo::new(&naive(2021, 3, 14, 3, 0), &tz).is_none());
1221            // Ambiguous time during the 2021 fall back overlap is not a gap
1222            assert!(GapInfo::new(&naive(2021, 11, 7, 1, 30), &tz).is_none());
1223        }
1224
1225        #[test]
1226        fn test_gap_info_america_new_york() {
1227            // Clocks went forward from 2021-03-14T02:00:00-05:00 to 2021-03-14T03:00:00-04:00
1228            let tz: Tz = "America/New_York".parse().unwrap();
1229            for local in [
1230                naive(2021, 3, 14, 2, 0),
1231                naive(2021, 3, 14, 2, 30),
1232                naive(2021, 3, 14, 2, 59),
1233            ] {
1234                assert!(tz.from_local_datetime(&local).single().is_none());
1235
1236                let gap = GapInfo::new(&local, &tz).unwrap();
1237                let (begin, begin_offset) = gap.begin.unwrap();
1238                assert_eq!(begin, naive(2021, 3, 14, 2, 0));
1239                assert_eq!(
1240                    begin_offset.fix(),
1241                    FixedOffset::west_opt(5 * 60 * 60).unwrap()
1242                );
1243
1244                let end = gap.end.unwrap();
1245                assert_eq!(end.naive_local(), naive(2021, 3, 14, 3, 0));
1246                assert_eq!(
1247                    end.offset().fix(),
1248                    FixedOffset::west_opt(4 * 60 * 60).unwrap()
1249                );
1250                assert_eq!(end, utc(2021, 3, 14, 7, 0));
1251                assert_eq!(end.timezone().to_string(), "America/New_York");
1252            }
1253        }
1254
1255        #[test]
1256        fn test_gap_info_europe_london() {
1257            // Clocks went forward from 2021-03-28T01:00:00+00:00 to 2021-03-28T02:00:00+01:00
1258            let tz: Tz = "Europe/London".parse().unwrap();
1259            let gap = GapInfo::new(&naive(2021, 3, 28, 1, 30), &tz).unwrap();
1260
1261            let (begin, begin_offset) = gap.begin.unwrap();
1262            assert_eq!(begin, naive(2021, 3, 28, 1, 0));
1263            assert_eq!(begin_offset.fix(), FixedOffset::east_opt(0).unwrap());
1264
1265            let end = gap.end.unwrap();
1266            assert_eq!(end.naive_local(), naive(2021, 3, 28, 2, 0));
1267            assert_eq!(end.offset().fix(), FixedOffset::east_opt(60 * 60).unwrap());
1268            assert_eq!(end, utc(2021, 3, 28, 1, 0));
1269        }
1270
1271        #[test]
1272        fn test_gap_info_australia_sydney() {
1273            // Clocks went forward from 2021-10-03T02:00:00+10:00 to 2021-10-03T03:00:00+11:00
1274            let tz: Tz = "Australia/Sydney".parse().unwrap();
1275            let gap = GapInfo::new(&naive(2021, 10, 3, 2, 30), &tz).unwrap();
1276
1277            let (begin, begin_offset) = gap.begin.unwrap();
1278            assert_eq!(begin, naive(2021, 10, 3, 2, 0));
1279            assert_eq!(
1280                begin_offset.fix(),
1281                FixedOffset::east_opt(10 * 60 * 60).unwrap()
1282            );
1283
1284            let end = gap.end.unwrap();
1285            assert_eq!(end.naive_local(), naive(2021, 10, 3, 3, 0));
1286            assert_eq!(
1287                end.offset().fix(),
1288                FixedOffset::east_opt(11 * 60 * 60).unwrap()
1289            );
1290            assert_eq!(end, utc(2021, 10, 2, 16, 0));
1291        }
1292    }
1293}