Skip to main content

dateoxide_core/
timezone.rs

1use crate::settings::{ParsedDateTime, Settings};
2use chrono::{FixedOffset, NaiveDateTime, TimeZone};
3use chrono_tz::Tz;
4use rustc_hash::FxHashMap;
5use std::str::FromStr;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum TzSpec {
9    Fixed(FixedOffset),
10    Iana(Tz),
11}
12
13/// Resolve a timezone name, abbreviation, or numeric offset checking custom overrides first.
14pub fn parse_tz_spec_with_abbrevs(
15    s: &str,
16    custom: &FxHashMap<String, String>,
17) -> Option<TzSpec> {
18    let trimmed = s.trim();
19    if trimmed.is_empty() {
20        return None;
21    }
22    if !custom.is_empty() {
23        let upper = trimmed.to_ascii_uppercase();
24        if let Some(mapped) = custom.get(&upper).or_else(|| custom.get(trimmed)) {
25            return parse_tz_spec(mapped);
26        }
27    }
28    parse_tz_spec(trimmed)
29}
30
31/// Resolve a timezone name, abbreviation, or numeric offset (e.g. "UTC", "Europe/Istanbul", "+03:00", "EST").
32pub fn parse_tz_spec(s: &str) -> Option<TzSpec> {
33    let trimmed = s.trim();
34    if trimmed.is_empty() {
35        return None;
36    }
37
38    // Fast path for Z / UTC / GMT
39    if trimmed.eq_ignore_ascii_case("z")
40        || trimmed.eq_ignore_ascii_case("utc")
41        || trimmed.eq_ignore_ascii_case("gmt")
42    {
43        return Some(TzSpec::Fixed(FixedOffset::east_opt(0)?));
44    }
45
46    // Numeric offsets: +03:00, -0500, +3, UTC+3, GMT-04:00
47    let offset_candidate = trimmed
48        .strip_prefix("UTC")
49        .or_else(|| trimmed.strip_prefix("utc"))
50        .or_else(|| trimmed.strip_prefix("GMT"))
51        .or_else(|| trimmed.strip_prefix("gmt"))
52        .unwrap_or(trimmed);
53
54    if let Some(off) = parse_numeric_offset(offset_candidate) {
55        return Some(TzSpec::Fixed(off));
56    }
57
58    // IANA timezone name (e.g., "Europe/Istanbul", "America/New_York")
59    if let Ok(tz) = Tz::from_str(trimmed) {
60        return Some(TzSpec::Iana(tz));
61    }
62
63    // Common timezone abbreviations
64    let secs = match trimmed.to_ascii_uppercase().as_str() {
65        "EST" => -5 * 3600,
66        "EDT" => -4 * 3600,
67        "CST" => -6 * 3600,
68        "CDT" => -5 * 3600,
69        "MST" => -7 * 3600,
70        "MDT" => -6 * 3600,
71        "PST" => -8 * 3600,
72        "PDT" => -7 * 3600,
73        "AKST" => -9 * 3600,
74        "AKDT" => -8 * 3600,
75        "HST" => -10 * 3600,
76        "CET" => 1 * 3600,
77        "CEST" => 2 * 3600,
78        "EET" => 2 * 3600,
79        "EEST" => 3 * 3600,
80        "WET" => 0,
81        "WEST" => 1 * 3600,
82        "BST" => 1 * 3600,
83        "TRT" => 3 * 3600,
84        "MSK" => 3 * 3600,
85        "GST" => 4 * 3600,
86        "IST" => 5 * 3600 + 1800,
87        "ICT" => 7 * 3600,
88        "SGT" | "HKT" | "AWST" => 8 * 3600,
89        "JST" | "KST" => 9 * 3600,
90        "AEST" => 10 * 3600,
91        "AEDT" => 11 * 3600,
92        "NZST" => 12 * 3600,
93        "NZDT" => 13 * 3600,
94        "BRT" | "ART" => -3 * 3600,
95        "WAT" => 1 * 3600,
96        "CAT" | "SAST" => 2 * 3600,
97        "EAT" => 3 * 3600,
98        _ => return None,
99    };
100
101    FixedOffset::east_opt(secs).map(TzSpec::Fixed)
102}
103
104pub fn parse_numeric_offset(s: &str) -> Option<FixedOffset> {
105    let b = s.as_bytes();
106    if b.len() < 2 {
107        return None;
108    }
109    let sign = match b[0] {
110        b'+' => 1,
111        b'-' => -1,
112        _ => return None,
113    };
114    let rest = &b[1..];
115    let (h, m): (i32, i32) = match rest.len() {
116        1 if rest[0].is_ascii_digit() => ((rest[0] - b'0') as i32, 0),
117        2 if rest[0].is_ascii_digit() && rest[1].is_ascii_digit() => {
118            (((rest[0] - b'0') * 10 + (rest[1] - b'0')) as i32, 0)
119        }
120        4 if rest.iter().all(|c| c.is_ascii_digit()) => {
121            let hh = ((rest[0] - b'0') * 10 + (rest[1] - b'0')) as i32;
122            let mm = ((rest[2] - b'0') * 10 + (rest[3] - b'0')) as i32;
123            (hh, mm)
124        }
125        5 if rest[2] == b':'
126            && rest[0].is_ascii_digit()
127            && rest[1].is_ascii_digit()
128            && rest[3].is_ascii_digit()
129            && rest[4].is_ascii_digit() =>
130        {
131            let hh = ((rest[0] - b'0') * 10 + (rest[1] - b'0')) as i32;
132            let mm = ((rest[3] - b'0') * 10 + (rest[4] - b'0')) as i32;
133            (hh, mm)
134        }
135        _ => return None,
136    };
137
138    if h > 23 || m > 59 {
139        return None;
140    }
141    FixedOffset::east_opt(sign * (h * 3600 + m * 60))
142}
143
144pub fn extract_trailing_timezone(input: &str) -> (&str, Option<TzSpec>) {
145    static EMPTY: std::sync::OnceLock<FxHashMap<String, String>> = std::sync::OnceLock::new();
146    let empty = EMPTY.get_or_init(FxHashMap::default);
147    extract_trailing_timezone_with_abbrevs(input, empty)
148}
149
150/// Peel off a trailing timezone token from a date string, honoring custom abbreviations.
151pub fn extract_trailing_timezone_with_abbrevs<'a>(
152    input: &'a str,
153    custom: &FxHashMap<String, String>,
154) -> (&'a str, Option<TzSpec>) {
155    let s = input.trim();
156    if s.is_empty() {
157        return (s, None);
158    }
159
160    // Handle trailing "(UTC)" / "(EST)" / "(CEST)"
161    if s.ends_with(')') {
162        if let Some(open) = s.rfind('(') {
163            let inside = &s[open + 1..s.len() - 1];
164            if let Some(tz) = parse_tz_spec_with_abbrevs(inside, custom) {
165                let prefix = s[..open].trim_end();
166                if !prefix.is_empty() {
167                    return (prefix, Some(tz));
168                }
169            }
170        }
171    }
172
173    // Handle trailing 'Z' attached to a timestamp like "2026-11-26T15:30:00Z"
174    if (s.ends_with('Z') || s.ends_with('z')) && s.len() >= 10 {
175        let prev = s.as_bytes()[s.len() - 2];
176        if prev.is_ascii_digit() {
177            return (&s[..s.len() - 1], FixedOffset::east_opt(0).map(TzSpec::Fixed));
178        }
179    }
180
181    // Handle trailing "+03:00" or "-0500" attached directly to time digits (e.g. 15:30:00+03:00)
182    if let Some(pos) = s.rfind(['+', '-']) {
183        if pos >= 8 {
184            let cand = &s[pos..];
185            if cand.len() >= 3 && cand.len() <= 6 {
186                let before = s.as_bytes()[pos - 1];
187                if (before.is_ascii_digit() && s[..pos].contains(':')) || before.is_ascii_whitespace()
188                {
189                    if let Some(off) = parse_numeric_offset(cand) {
190                        let prefix = s[..pos].trim_end();
191                        if !prefix.is_empty() {
192                            return (prefix, Some(TzSpec::Fixed(off)));
193                        }
194                    }
195                }
196            }
197        }
198    }
199
200    // Handle whitespace-separated trailing token: "EST", "UTC+3", "Europe/Istanbul", or custom abbrev
201    if let Some(sp) = s.rfind(|c: char| c.is_whitespace()) {
202        let last = &s[sp + 1..];
203        let upper = last.to_ascii_uppercase();
204        let is_custom = !custom.is_empty() && (custom.contains_key(&upper) || custom.contains_key(last));
205        let looks_like_tz = is_custom
206            || last.contains('/')
207            || last.contains('+')
208            || last.contains('-')
209            || last.eq_ignore_ascii_case("utc")
210            || last.eq_ignore_ascii_case("gmt")
211            || (last.len() >= 3 && last.len() <= 5 && last.chars().all(|c| c.is_ascii_uppercase()));
212        if looks_like_tz {
213            if let Some(tz) = parse_tz_spec_with_abbrevs(last, custom) {
214                let prefix = s[..sp].trim_end();
215                if !prefix.is_empty() {
216                    return (prefix, Some(tz));
217                }
218            }
219        }
220    }
221
222    (s, None)
223}
224
225/// Equivalent of `dateparser.timezone_parser.pop_tz_offset_from_string`.
226pub fn pop_tz_offset_from_string(
227    input: &str,
228    custom: Option<&FxHashMap<String, String>>,
229) -> (String, Option<TzSpec>) {
230    let (cleaned, tz) = match custom {
231        Some(map) => extract_trailing_timezone_with_abbrevs(input, map),
232        None => extract_trailing_timezone(input),
233    };
234    (cleaned.to_string(), tz)
235}
236
237/// Apply parsed timezone + Settings (`TIMEZONE`, `TO_TIMEZONE`, `RETURN_AS_TIMEZONE_AWARE`)
238/// to produce the final `ParsedDateTime`.
239pub fn finalize_datetime(
240    naive: NaiveDateTime,
241    extracted_tz: Option<TzSpec>,
242    settings: &Settings,
243) -> ParsedDateTime {
244    let source_tz = extracted_tz.or_else(|| {
245        settings
246            .timezone
247            .as_deref()
248            .and_then(|t| parse_tz_spec_with_abbrevs(t, &settings.timezone_abbreviations))
249    });
250
251    let target_tz = settings
252        .to_timezone
253        .as_deref()
254        .and_then(|t| parse_tz_spec_with_abbrevs(t, &settings.timezone_abbreviations));
255
256    let want_aware = match settings.return_as_timezone_aware {
257        Some(flag) => flag,
258        None => extracted_tz.is_some(),
259    };
260
261    if let Some(tgt) = target_tz {
262        let utc_dt = match source_tz {
263            Some(TzSpec::Fixed(off)) => off
264                .from_local_datetime(&naive)
265                .single()
266                .map(|d| d.to_utc())
267                .unwrap_or_else(|| naive.and_utc()),
268            Some(TzSpec::Iana(tz)) => tz
269                .from_local_datetime(&naive)
270                .earliest()
271                .map(|d| d.to_utc())
272                .unwrap_or_else(|| naive.and_utc()),
273            None => chrono::Local
274                .from_local_datetime(&naive)
275                .earliest()
276                .map(|d| d.to_utc())
277                .unwrap_or_else(|| naive.and_utc()),
278        };
279
280        return match tgt {
281            TzSpec::Fixed(off) => {
282                let converted = utc_dt.with_timezone(&off);
283                if want_aware {
284                    ParsedDateTime::FixedOffset(converted)
285                } else {
286                    ParsedDateTime::Naive(converted.naive_local())
287                }
288            }
289            TzSpec::Iana(tz) => {
290                let converted = utc_dt.with_timezone(&tz);
291                if want_aware {
292                    ParsedDateTime::Tz(converted)
293                } else {
294                    ParsedDateTime::Naive(converted.naive_local())
295                }
296            }
297        };
298    }
299
300    if want_aware {
301        match source_tz {
302            Some(TzSpec::Fixed(off)) => {
303                if let Some(dt) = off.from_local_datetime(&naive).single() {
304                    return ParsedDateTime::FixedOffset(dt);
305                }
306            }
307            Some(TzSpec::Iana(tz)) => {
308                if let Some(dt) = tz.from_local_datetime(&naive).earliest() {
309                    return ParsedDateTime::Tz(dt);
310                }
311            }
312            None => {
313                if let Some(dt) = chrono::Local.from_local_datetime(&naive).earliest() {
314                    return ParsedDateTime::FixedOffset(dt.fixed_offset());
315                }
316            }
317        }
318    }
319
320    ParsedDateTime::Naive(naive)
321}