1use arrow_schema::ArrowError;
31use chrono::{DateTime, FixedOffset, NaiveDateTime};
32pub use private::{Tz, TzOffset};
33
34pub 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
56fn parse_fixed_offset(tz: &str) -> Option<FixedOffset> {
58 let bytes = tz.as_bytes();
59
60 let mut values = match bytes.len() {
61 6 if bytes[3] == b':' => [bytes[1], bytes[2], bytes[4], bytes[5]],
63 5 => [bytes[1], bytes[2], bytes[3], bytes[4]],
65 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 #[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 struct NamedTz {
117 name: &'static str,
118 tz: JiffTimeZone,
119 }
120
121 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 fn bundled_tz(name: &str) -> Option<JiffTimeZone> {
131 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 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 .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 .ok_or_else(|| {
165 ArrowError::ParseError(format!(
166 "Invalid timezone \"{name}\": failed to parse timezone"
167 ))
168 })
169 }
170
171 #[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 #[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 FixedOffset::east_opt(offset.seconds()).expect("timezone offset within a day")
211 }
212
213 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 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 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 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 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 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 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 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 assert!(matches!(
403 tz.offset_from_local_datetime(&at(3, 10, 2, 30)),
404 LocalResult::None
405 ));
406 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 assert!(matches!(
416 tz.offset_from_local_date(&NaiveDate::from_ymd_opt(2024, 3, 10).unwrap()),
417 LocalResult::Single(_)
418 ));
419 }
420
421 #[test]
423 fn test_dst_applies_after_2099() {
424 let hours = |h| FixedOffset::east_opt(h * 60 * 60).unwrap();
425 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 #[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 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 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 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 #[cfg(feature = "chrono-tz")]
578 mod compare_with_chrono_tz {
579 use super::*;
580 use std::collections::BTreeSet;
581
582 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 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 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 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 let mut samples: Vec<_> = (START..END).step_by(WEEK).map(at).collect();
708
709 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 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 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 #[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 #[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 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 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 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 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 #[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 #[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 None
1051 }
1052}
1053
1054#[derive(Debug, Clone, Copy)]
1101pub struct GapInfo {
1102 pub begin: Option<(NaiveDateTime, TzOffset)>,
1111
1112 pub end: Option<DateTime<Tz>>,
1114}
1115
1116impl GapInfo {
1117 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 #[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 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 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 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 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 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}