1use arrow_schema::ArrowError;
21use chrono::{DateTime, FixedOffset, NaiveDateTime};
22pub use private::{Tz, TzOffset};
23
24fn parse_fixed_offset(tz: &str) -> Option<FixedOffset> {
26 let bytes = tz.as_bytes();
27
28 let mut values = match bytes.len() {
29 6 if bytes[3] == b':' => [bytes[1], bytes[2], bytes[4], bytes[5]],
31 5 => [bytes[1], bytes[2], bytes[3], bytes[4]],
33 3 => [bytes[1], bytes[2], b'0', b'0'],
35 _ => return None,
36 };
37 values.iter_mut().for_each(|x| *x = x.wrapping_sub(b'0'));
38 if values.iter().any(|x| *x > 9) {
39 return None;
40 }
41 let secs =
42 (values[0] * 10 + values[1]) as i32 * 60 * 60 + (values[2] * 10 + values[3]) as i32 * 60;
43
44 match bytes[0] {
45 b'+' => FixedOffset::east_opt(secs),
46 b'-' => FixedOffset::west_opt(secs),
47 _ => None,
48 }
49}
50
51#[cfg(feature = "chrono-tz")]
52mod private {
53 use super::*;
54 use chrono::offset::TimeZone;
55 use chrono::{LocalResult, NaiveDate, NaiveDateTime, Offset};
56 use std::fmt::Display;
57 use std::str::FromStr;
58
59 #[derive(Debug, Copy, Clone)]
61 pub struct TzOffset {
62 tz: Tz,
63 offset: FixedOffset,
64 }
65
66 impl std::fmt::Display for TzOffset {
67 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68 self.offset.fmt(f)
69 }
70 }
71
72 impl Offset for TzOffset {
73 fn fix(&self) -> FixedOffset {
74 self.offset
75 }
76 }
77
78 #[derive(Debug, Copy, Clone)]
80 pub struct Tz(TzInner);
81
82 #[derive(Debug, Copy, Clone)]
83 enum TzInner {
84 Timezone(chrono_tz::Tz),
85 Offset(FixedOffset),
86 }
87
88 impl FromStr for Tz {
89 type Err = ArrowError;
90
91 fn from_str(tz: &str) -> Result<Self, Self::Err> {
92 match parse_fixed_offset(tz) {
93 Some(offset) => Ok(Self(TzInner::Offset(offset))),
94 None => Ok(Self(TzInner::Timezone(tz.parse().map_err(|e| {
95 ArrowError::ParseError(format!("Invalid timezone \"{tz}\": {e}"))
96 })?))),
97 }
98 }
99 }
100
101 impl Display for Tz {
102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 match self.0 {
104 TzInner::Timezone(tz) => tz.fmt(f),
105 TzInner::Offset(offset) => offset.fmt(f),
106 }
107 }
108 }
109
110 macro_rules! tz {
111 ($s:ident, $tz:ident, $b:block) => {
112 match $s.0 {
113 TzInner::Timezone($tz) => $b,
114 TzInner::Offset($tz) => $b,
115 }
116 };
117 }
118
119 impl TimeZone for Tz {
120 type Offset = TzOffset;
121
122 fn from_offset(offset: &Self::Offset) -> Self {
123 offset.tz
124 }
125
126 fn offset_from_local_date(&self, local: &NaiveDate) -> LocalResult<Self::Offset> {
127 tz!(self, tz, {
128 tz.offset_from_local_date(local).map(|x| TzOffset {
129 tz: *self,
130 offset: x.fix(),
131 })
132 })
133 }
134
135 fn offset_from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<Self::Offset> {
136 tz!(self, tz, {
137 tz.offset_from_local_datetime(local).map(|x| TzOffset {
138 tz: *self,
139 offset: x.fix(),
140 })
141 })
142 }
143
144 fn offset_from_utc_date(&self, utc: &NaiveDate) -> Self::Offset {
145 tz!(self, tz, {
146 TzOffset {
147 tz: *self,
148 offset: tz.offset_from_utc_date(utc).fix(),
149 }
150 })
151 }
152
153 fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> Self::Offset {
154 tz!(self, tz, {
155 TzOffset {
156 tz: *self,
157 offset: tz.offset_from_utc_datetime(utc).fix(),
158 }
159 })
160 }
161 }
162
163 #[inline]
164 pub(super) fn new_gap_info(local: &NaiveDateTime, tz: &Tz) -> Option<GapInfo> {
165 let TzInner::Timezone(ctz) = &tz.0 else {
166 return None;
167 };
168 chrono_tz::GapInfo::new(local, ctz).map(|gi| GapInfo {
169 begin: gi.begin.map(|(ndt, ctz)| {
170 (
171 ndt,
172 TzOffset {
173 tz: *tz,
174 offset: ctz.fix(),
175 },
176 )
177 }),
178 end: gi.end.map(|dt| dt.with_timezone(tz)),
179 })
180 }
181
182 #[cfg(test)]
183 mod tests {
184 use super::*;
185 use chrono::{Timelike, Utc};
186
187 #[test]
188 fn test_with_timezone() {
189 let vals = [
190 Utc.timestamp_millis_opt(37800000).unwrap(),
191 Utc.timestamp_millis_opt(86339000).unwrap(),
192 ];
193
194 assert_eq!(10, vals[0].hour());
195 assert_eq!(23, vals[1].hour());
196
197 let tz: Tz = "America/Los_Angeles".parse().unwrap();
198
199 assert_eq!(2, vals[0].with_timezone(&tz).hour());
200 assert_eq!(15, vals[1].with_timezone(&tz).hour());
201 }
202
203 #[test]
204 fn test_using_chrono_tz_and_utc_naive_date_time() {
205 let sydney_tz = "Australia/Sydney".to_string();
206 let tz: Tz = sydney_tz.parse().unwrap();
207 let sydney_offset_without_dst = FixedOffset::east_opt(10 * 60 * 60).unwrap();
208 let sydney_offset_with_dst = FixedOffset::east_opt(11 * 60 * 60).unwrap();
209 let utc_just_before_sydney_dst_ends = NaiveDate::from_ymd_opt(2021, 4, 3)
221 .unwrap()
222 .and_hms_nano_opt(15, 30, 0, 0)
223 .unwrap();
224 assert_eq!(
225 tz.offset_from_utc_datetime(&utc_just_before_sydney_dst_ends)
226 .fix(),
227 sydney_offset_with_dst
228 );
229 let utc_just_after_sydney_dst_ends = NaiveDate::from_ymd_opt(2021, 4, 3)
231 .unwrap()
232 .and_hms_nano_opt(16, 30, 0, 0)
233 .unwrap();
234 assert_eq!(
235 tz.offset_from_utc_datetime(&utc_just_after_sydney_dst_ends)
236 .fix(),
237 sydney_offset_without_dst
238 );
239 let utc_just_before_sydney_dst_starts = NaiveDate::from_ymd_opt(2021, 10, 2)
241 .unwrap()
242 .and_hms_nano_opt(15, 30, 0, 0)
243 .unwrap();
244 assert_eq!(
245 tz.offset_from_utc_datetime(&utc_just_before_sydney_dst_starts)
246 .fix(),
247 sydney_offset_without_dst
248 );
249 let utc_just_after_sydney_dst_starts = NaiveDate::from_ymd_opt(2022, 10, 2)
251 .unwrap()
252 .and_hms_nano_opt(16, 30, 0, 0)
253 .unwrap();
254 assert_eq!(
255 tz.offset_from_utc_datetime(&utc_just_after_sydney_dst_starts)
256 .fix(),
257 sydney_offset_with_dst
258 );
259 }
260
261 fn naive(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> NaiveDateTime {
262 NaiveDate::from_ymd_opt(y, mo, d)
263 .unwrap()
264 .and_hms_opt(h, mi, 0)
265 .unwrap()
266 }
267
268 fn utc(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> chrono::DateTime<Utc> {
269 Utc.with_ymd_and_hms(y, mo, d, h, mi, 0).unwrap()
270 }
271
272 #[test]
273 fn test_gap_info_not_in_gap() {
274 let tz: Tz = "America/New_York".parse().unwrap();
275 assert!(GapInfo::new(&naive(2021, 3, 14, 1, 59), &tz).is_none());
277 assert!(GapInfo::new(&naive(2021, 3, 14, 3, 0), &tz).is_none());
278 assert!(GapInfo::new(&naive(2021, 11, 7, 1, 30), &tz).is_none());
280 }
281
282 #[test]
283 fn test_gap_info_america_new_york() {
284 let tz: Tz = "America/New_York".parse().unwrap();
286 for local in [
287 naive(2021, 3, 14, 2, 0),
288 naive(2021, 3, 14, 2, 30),
289 naive(2021, 3, 14, 2, 59),
290 ] {
291 assert!(tz.from_local_datetime(&local).single().is_none());
292
293 let gap = GapInfo::new(&local, &tz).unwrap();
294 let (begin, begin_offset) = gap.begin.unwrap();
295 assert_eq!(begin, naive(2021, 3, 14, 2, 0));
296 assert_eq!(
297 begin_offset.fix(),
298 FixedOffset::west_opt(5 * 60 * 60).unwrap()
299 );
300
301 let end = gap.end.unwrap();
302 assert_eq!(end.naive_local(), naive(2021, 3, 14, 3, 0));
303 assert_eq!(
304 end.offset().fix(),
305 FixedOffset::west_opt(4 * 60 * 60).unwrap()
306 );
307 assert_eq!(end, utc(2021, 3, 14, 7, 0));
308 assert_eq!(end.timezone().to_string(), "America/New_York");
309 }
310 }
311
312 #[test]
313 fn test_gap_info_europe_london() {
314 let tz: Tz = "Europe/London".parse().unwrap();
316 let gap = GapInfo::new(&naive(2021, 3, 28, 1, 30), &tz).unwrap();
317
318 let (begin, begin_offset) = gap.begin.unwrap();
319 assert_eq!(begin, naive(2021, 3, 28, 1, 0));
320 assert_eq!(begin_offset.fix(), FixedOffset::east_opt(0).unwrap());
321
322 let end = gap.end.unwrap();
323 assert_eq!(end.naive_local(), naive(2021, 3, 28, 2, 0));
324 assert_eq!(end.offset().fix(), FixedOffset::east_opt(60 * 60).unwrap());
325 assert_eq!(end, utc(2021, 3, 28, 1, 0));
326 }
327
328 #[test]
329 fn test_gap_info_australia_sydney() {
330 let tz: Tz = "Australia/Sydney".parse().unwrap();
332 let gap = GapInfo::new(&naive(2021, 10, 3, 2, 30), &tz).unwrap();
333
334 let (begin, begin_offset) = gap.begin.unwrap();
335 assert_eq!(begin, naive(2021, 10, 3, 2, 0));
336 assert_eq!(
337 begin_offset.fix(),
338 FixedOffset::east_opt(10 * 60 * 60).unwrap()
339 );
340
341 let end = gap.end.unwrap();
342 assert_eq!(end.naive_local(), naive(2021, 10, 3, 3, 0));
343 assert_eq!(
344 end.offset().fix(),
345 FixedOffset::east_opt(11 * 60 * 60).unwrap()
346 );
347 assert_eq!(end, utc(2021, 10, 2, 16, 0));
348 }
349
350 #[test]
351 fn test_timezone_display() {
352 let test_cases = ["UTC", "America/Los_Angeles", "-08:00", "+05:30"];
353 for &case in &test_cases {
354 let tz: Tz = case.parse().unwrap();
355 assert_eq!(tz.to_string(), case);
356 }
357 }
358 }
359}
360
361#[cfg(not(feature = "chrono-tz"))]
362mod private {
363 use super::*;
364 use chrono::offset::TimeZone;
365 use chrono::{LocalResult, NaiveDate, NaiveDateTime, Offset};
366 use std::str::FromStr;
367
368 #[derive(Debug, Copy, Clone)]
370 pub struct TzOffset(FixedOffset);
371
372 impl std::fmt::Display for TzOffset {
373 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374 self.0.fmt(f)
375 }
376 }
377
378 impl Offset for TzOffset {
379 fn fix(&self) -> FixedOffset {
380 self.0
381 }
382 }
383
384 #[derive(Debug, Copy, Clone)]
386 pub struct Tz(FixedOffset);
387
388 impl FromStr for Tz {
389 type Err = ArrowError;
390
391 fn from_str(tz: &str) -> Result<Self, Self::Err> {
392 let offset = parse_fixed_offset(tz).ok_or_else(|| {
393 ArrowError::ParseError(format!(
394 "Invalid timezone \"{tz}\": only offset based timezones supported without chrono-tz feature"
395 ))
396 })?;
397 Ok(Self(offset))
398 }
399 }
400
401 impl TimeZone for Tz {
402 type Offset = TzOffset;
403
404 fn from_offset(offset: &Self::Offset) -> Self {
405 Self(offset.0)
406 }
407
408 fn offset_from_local_date(&self, local: &NaiveDate) -> LocalResult<Self::Offset> {
409 self.0.offset_from_local_date(local).map(TzOffset)
410 }
411
412 fn offset_from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<Self::Offset> {
413 self.0.offset_from_local_datetime(local).map(TzOffset)
414 }
415
416 fn offset_from_utc_date(&self, utc: &NaiveDate) -> Self::Offset {
417 TzOffset(self.0.offset_from_utc_date(utc).fix())
418 }
419
420 fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> Self::Offset {
421 TzOffset(self.0.offset_from_utc_datetime(utc).fix())
422 }
423 }
424
425 #[inline]
426 pub(super) fn new_gap_info(_local: &NaiveDateTime, _tz: &Tz) -> Option<GapInfo> {
427 None
429 }
430}
431
432#[derive(Debug, Clone, Copy)]
479pub struct GapInfo {
480 pub begin: Option<(NaiveDateTime, TzOffset)>,
489
490 pub end: Option<DateTime<Tz>>,
492}
493
494impl GapInfo {
495 pub fn new(local: &NaiveDateTime, tz: &Tz) -> Option<Self> {
503 private::new_gap_info(local, tz)
504 }
505}
506
507#[cfg(test)]
508mod tests {
509 use super::*;
510 use chrono::{NaiveDate, Offset, TimeZone};
511
512 #[test]
513 fn test_with_offset() {
514 let t = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
515
516 let tz: Tz = "-00:00".parse().unwrap();
517 assert_eq!(tz.offset_from_utc_date(&t).fix().local_minus_utc(), 0);
518 let tz: Tz = "+00:00".parse().unwrap();
519 assert_eq!(tz.offset_from_utc_date(&t).fix().local_minus_utc(), 0);
520
521 let tz: Tz = "-10:00".parse().unwrap();
522 assert_eq!(
523 tz.offset_from_utc_date(&t).fix().local_minus_utc(),
524 -10 * 60 * 60
525 );
526 let tz: Tz = "+09:00".parse().unwrap();
527 assert_eq!(
528 tz.offset_from_utc_date(&t).fix().local_minus_utc(),
529 9 * 60 * 60
530 );
531
532 let tz = "+09".parse::<Tz>().unwrap();
533 assert_eq!(
534 tz.offset_from_utc_date(&t).fix().local_minus_utc(),
535 9 * 60 * 60
536 );
537
538 let tz = "+0900".parse::<Tz>().unwrap();
539 assert_eq!(
540 tz.offset_from_utc_date(&t).fix().local_minus_utc(),
541 9 * 60 * 60
542 );
543
544 let err = "+9:00".parse::<Tz>().unwrap_err().to_string();
545 assert!(err.contains("Invalid timezone"), "{}", err);
546 }
547
548 #[test]
549 fn test_gap_info_fixed_offset() {
550 let times = [
551 NaiveDate::from_ymd_opt(2000, 1, 1)
552 .unwrap()
553 .and_hms_opt(0, 0, 0)
554 .unwrap(),
555 NaiveDate::from_ymd_opt(2021, 3, 14)
557 .unwrap()
558 .and_hms_opt(2, 30, 0)
559 .unwrap(),
560 NaiveDate::from_ymd_opt(2021, 3, 28)
561 .unwrap()
562 .and_hms_opt(1, 30, 0)
563 .unwrap(),
564 ];
565
566 for tz in ["+00:00", "-05:00", "+01:00", "+09:30"] {
567 let tz: Tz = tz.parse().unwrap();
568 for t in × {
569 assert!(GapInfo::new(t, &tz).is_none(), "{tz:?} {t}");
570 }
571 }
572 }
573}