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 & world timezone abbreviations
64    let secs = match trimmed.to_ascii_uppercase().as_str() {
65        // UTC / Universal
66        "UT" | "WT" | "AZOST" | "EGST" => 0,
67        // Americas
68        "SST" | "NUT" => -11 * 3600,
69        "HST" | "HAST" | "CKT" | "TAHT" => -10 * 3600,
70        "MART" | "MIT" => -9 * 3600 - 1800,
71        "AKST" | "HADT" | "HDT" => -9 * 3600,
72        "PST" | "PT" | "AKDT" => -8 * 3600,
73        "MST" | "PDT" => -7 * 3600,
74        "CST" | "MDT" => -6 * 3600,
75        "EST" | "CDT" | "ACT" | "COT" | "ECT" | "ET" | "PET" => -5 * 3600,
76        "AST" | "EDT" | "BOT" | "CLT" | "FKT" | "GYT" | "PYT" | "VET" => -4 * 3600,
77        "NST" | "NT" => -3 * 3600 - 1800,
78        "ADT" | "ARST" | "ART" | "BRT" | "CLST" | "FKST" | "GFT" | "PYST" | "SRT" | "UYT" => -3 * 3600,
79        "NDT" => -2 * 3600 - 1800,
80        "BRST" | "FNT" | "UYST" => -2 * 3600,
81        "CVT" | "AZOT" | "EGT" => -1 * 3600,
82        // Europe / Africa / Middle East
83        "WET" => 0,
84        "CET" | "WEST" | "BST" | "WAT" | "MET" | "MEZ" | "DFT" => 1 * 3600,
85        "CEST" | "EET" | "CAT" | "SAST" | "MEST" | "MESZ" | "WAST" => 2 * 3600,
86        "EEST" | "TRT" | "MSK" | "EAT" | "FET" | "IDT" => 3 * 3600,
87        "IRST" => 3 * 3600 + 1800,
88        "GST" | "AMT" | "AZT" | "GET" | "MSD" | "MUT" | "RET" | "SCT" | "SAMT" => 4 * 3600,
89        "IRDT" | "AFT" => 4 * 3600 + 1800,
90        // Asia / Pacific
91        "PKT" | "UZT" | "TJT" | "TMT" | "MVT" | "YEKT" | "ORAT" | "AQTT" => 5 * 3600,
92        "IST" | "SLT" => 5 * 3600 + 1800,
93        "NPT" => 5 * 3600 + 2700,
94        "ALMT" | "BTT" | "IOT" | "KGT" | "OMST" | "QYZT" | "VOST" | "PKST" | "XJT" | "BDT" => 6 * 3600,
95        "MMT" | "CCT" => 6 * 3600 + 1800,
96        "ICT" | "WIB" | "THA" | "KRAT" | "NOVT" | "CXT" | "HOVT" => 7 * 3600,
97        "SGT" | "HKT" | "AWST" | "PHT" | "MYT" | "WITA" | "BNT" | "ULAT" | "IRKT" | "CHOT" | "WST" => 8 * 3600,
98        "ACWST" => 8 * 3600 + 2700,
99        "JST" | "KST" | "WIT" | "TLT" | "YAKT" => 9 * 3600,
100        "ACST" => 9 * 3600 + 1800,
101        "AEST" | "CHST" | "PGT" | "VLAT" => 10 * 3600,
102        "ACDT" | "LHST" => 10 * 3600 + 1800,
103        "AEDT" | "SBT" | "VUT" | "NCT" | "MAGT" | "KOST" | "PONT" | "LHDT" => 11 * 3600,
104        "NFT" => 11 * 3600 + 1800,
105        "NZST" | "FJT" | "GILT" | "MHT" | "TVT" | "ANAT" | "PETT" | "WFT" => 12 * 3600,
106        "CHAST" => 12 * 3600 + 2700,
107        "NZDT" | "FJST" | "TOT" | "PHOT" | "WSST" => 13 * 3600,
108        "CHADT" => 13 * 3600 + 2700,
109        "LINT" | "WSDT" => 14 * 3600,
110        _ => return None,
111    };
112
113    FixedOffset::east_opt(secs).map(TzSpec::Fixed)
114}
115
116pub fn parse_numeric_offset(s: &str) -> Option<FixedOffset> {
117    let b = s.as_bytes();
118    if b.len() < 2 {
119        return None;
120    }
121    let sign = match b[0] {
122        b'+' => 1,
123        b'-' => -1,
124        _ => return None,
125    };
126    let rest = &b[1..];
127    let (h, m): (i32, i32) = match rest.len() {
128        1 if rest[0].is_ascii_digit() => ((rest[0] - b'0') as i32, 0),
129        2 if rest[0].is_ascii_digit() && rest[1].is_ascii_digit() => {
130            (((rest[0] - b'0') * 10 + (rest[1] - b'0')) as i32, 0)
131        }
132        4 if rest.iter().all(|c| c.is_ascii_digit()) => {
133            let hh = ((rest[0] - b'0') * 10 + (rest[1] - b'0')) as i32;
134            let mm = ((rest[2] - b'0') * 10 + (rest[3] - b'0')) as i32;
135            (hh, mm)
136        }
137        5 if rest[2] == b':'
138            && rest[0].is_ascii_digit()
139            && rest[1].is_ascii_digit()
140            && rest[3].is_ascii_digit()
141            && rest[4].is_ascii_digit() =>
142        {
143            let hh = ((rest[0] - b'0') * 10 + (rest[1] - b'0')) as i32;
144            let mm = ((rest[3] - b'0') * 10 + (rest[4] - b'0')) as i32;
145            (hh, mm)
146        }
147        _ => return None,
148    };
149
150    if h > 23 || m > 59 {
151        return None;
152    }
153    FixedOffset::east_opt(sign * (h * 3600 + m * 60))
154}
155
156pub fn extract_trailing_timezone(input: &str) -> (&str, Option<TzSpec>) {
157    static EMPTY: std::sync::OnceLock<FxHashMap<String, String>> = std::sync::OnceLock::new();
158    let empty = EMPTY.get_or_init(FxHashMap::default);
159    extract_trailing_timezone_with_abbrevs(input, empty)
160}
161
162fn extract_trailing_timezone_non_paren<'a>(
163    s: &'a str,
164    custom: &FxHashMap<String, String>,
165) -> (&'a str, Option<TzSpec>) {
166    // Handle trailing 'Z' attached to a timestamp like "2026-11-26T15:30:00Z"
167    if (s.ends_with('Z') || s.ends_with('z')) && s.len() >= 10 {
168        let prev = s.as_bytes()[s.len() - 2];
169        if prev.is_ascii_digit() {
170            return (&s[..s.len() - 1], FixedOffset::east_opt(0).map(TzSpec::Fixed));
171        }
172    }
173
174    // Handle trailing "+03:00" or "-0500" attached directly to time digits (e.g. 15:30:00+03:00)
175    if let Some(pos) = s.rfind(['+', '-']) {
176        if pos >= 8 {
177            let cand = &s[pos..];
178            if cand.len() >= 3 && cand.len() <= 6 {
179                let before = s.as_bytes()[pos - 1];
180                if (before.is_ascii_digit() && s[..pos].contains(':')) || before.is_ascii_whitespace()
181                {
182                    if let Some(off) = parse_numeric_offset(cand) {
183                        let prefix = s[..pos].trim_end();
184                        if !prefix.is_empty() {
185                            return (prefix, Some(TzSpec::Fixed(off)));
186                        }
187                    }
188                }
189            }
190        }
191    }
192
193    // Handle whitespace-separated trailing token: "EST", "UTC+3", "Europe/Istanbul", or custom abbrev
194    if let Some(sp) = s.rfind(|c: char| c.is_whitespace()) {
195        let last = &s[sp + 1..];
196        let upper = last.to_ascii_uppercase();
197        let is_custom = !custom.is_empty() && (custom.contains_key(&upper) || custom.contains_key(last));
198        let is_two_letter_tz = last.len() == 2
199            && matches!(last, "UT" | "ET" | "PT")
200            && s[..sp]
201                .trim_end()
202                .split_whitespace()
203                .next_back()
204                .map(|prev| prev.contains(':'))
205                .unwrap_or(false);
206        let looks_like_tz = is_custom
207            || is_two_letter_tz
208            || last.contains('/')
209            || last.contains('+')
210            || last.contains('-')
211            || last.eq_ignore_ascii_case("utc")
212            || last.eq_ignore_ascii_case("gmt")
213            || (last.len() >= 3 && last.len() <= 5 && last.chars().all(|c| c.is_ascii_uppercase()));
214        if looks_like_tz {
215            if let Some(tz) = parse_tz_spec_with_abbrevs(last, custom) {
216                let prefix = s[..sp].trim_end();
217                if !prefix.is_empty() {
218                    return (prefix, Some(tz));
219                }
220            }
221        }
222    }
223
224    (s, None)
225}
226
227/// Peel off a trailing timezone token from a date string, honoring custom abbreviations
228/// and JavaScript / RFC-2822 parenthesized timezone comments such as
229/// `"Thu Nov 26 2026 14:30:00 GMT+0300 (Turkey Time)"`.
230pub fn extract_trailing_timezone_with_abbrevs<'a>(
231    input: &'a str,
232    custom: &FxHashMap<String, String>,
233) -> (&'a str, Option<TzSpec>) {
234    let s = input.trim();
235    if s.is_empty() {
236        return (s, None);
237    }
238
239    if s.ends_with(')') {
240        if let Some(open) = s.rfind('(') {
241            if open > 0 {
242                let inside = s[open + 1..s.len() - 1].trim();
243                let prefix = s[..open].trim_end();
244                if !prefix.is_empty() {
245                    let (prefix2, prefix_tz) = extract_trailing_timezone_non_paren(prefix, custom);
246                    if prefix_tz.is_some() && !prefix2.is_empty() {
247                        return (prefix2, prefix_tz);
248                    }
249                    if let Some(paren_tz) = parse_tz_spec_with_abbrevs(inside, custom) {
250                        return (prefix, Some(paren_tz));
251                    }
252                }
253            }
254        }
255    }
256
257    extract_trailing_timezone_non_paren(s, custom)
258}
259
260/// Extract a Unix `ctime` / `date` mid-string timezone token immediately preceding a trailing
261/// 4-digit year (e.g. `"Thu Nov 26 14:30:00 UTC 2026"`, `"Mon Jan 15 09:00:00 CEST 2026"`).
262pub fn extract_embedded_timezone_before_year(
263    input: &str,
264    custom: &FxHashMap<String, String>,
265) -> Option<(String, TzSpec)> {
266    let tokens: Vec<&str> = input.split_whitespace().collect();
267    if tokens.len() < 4 {
268        return None;
269    }
270    let len = tokens.len();
271    let year_tok = tokens[len - 1];
272    if year_tok.len() != 4 || !year_tok.bytes().all(|b| b.is_ascii_digit()) {
273        return None;
274    }
275    let year: u32 = year_tok.parse().ok()?;
276    if !(1000..=2999).contains(&year) {
277        return None;
278    }
279
280    let tz_tok = tokens[len - 2];
281    let time_tok = tokens[len - 3];
282    if !time_tok.contains(':') {
283        return None;
284    }
285
286    let upper = tz_tok.to_ascii_uppercase();
287    let is_custom = !custom.is_empty() && (custom.contains_key(&upper) || custom.contains_key(tz_tok));
288    let looks_like_tz = is_custom
289        || tz_tok.contains('/')
290        || tz_tok.contains('+')
291        || tz_tok.contains('-')
292        || tz_tok.eq_ignore_ascii_case("utc")
293        || tz_tok.eq_ignore_ascii_case("gmt")
294        || matches!(tz_tok, "UT" | "ET" | "PT")
295        || (tz_tok.len() >= 3
296            && tz_tok.len() <= 5
297            && tz_tok.chars().all(|c| c.is_ascii_uppercase()));
298    if !looks_like_tz {
299        return None;
300    }
301
302    let tz = parse_tz_spec_with_abbrevs(tz_tok, custom)?;
303    let mut cleaned_tokens = Vec::with_capacity(len - 1);
304    cleaned_tokens.extend_from_slice(&tokens[..len - 2]);
305    cleaned_tokens.push(year_tok);
306    Some((cleaned_tokens.join(" "), tz))
307}
308
309/// Equivalent of `dateparser.timezone_parser.pop_tz_offset_from_string`.
310pub fn pop_tz_offset_from_string(
311    input: &str,
312    custom: Option<&FxHashMap<String, String>>,
313) -> (String, Option<TzSpec>) {
314    let (cleaned, tz) = match custom {
315        Some(map) => extract_trailing_timezone_with_abbrevs(input, map),
316        None => extract_trailing_timezone(input),
317    };
318    (cleaned.to_string(), tz)
319}
320
321/// Resolve a local `NaiveDateTime` inside an IANA timezone, shifting past DST spring-forward gaps.
322#[inline]
323fn resolve_iana_local(tz: Tz, naive: NaiveDateTime) -> chrono::DateTime<Tz> {
324    if let Some(dt) = tz.from_local_datetime(&naive).earliest() {
325        return dt;
326    }
327    let shifted = naive + chrono::Duration::hours(1);
328    if let Some(dt) = tz.from_local_datetime(&shifted).earliest() {
329        return dt;
330    }
331    naive.and_utc().with_timezone(&tz)
332}
333
334/// Apply parsed timezone + Settings (`TIMEZONE`, `TO_TIMEZONE`, `RETURN_AS_TIMEZONE_AWARE`)
335/// to produce the final `ParsedDateTime`.
336pub fn finalize_datetime(
337    naive: NaiveDateTime,
338    extracted_tz: Option<TzSpec>,
339    settings: &Settings,
340) -> ParsedDateTime {
341    let source_tz = extracted_tz.or_else(|| {
342        settings
343            .timezone
344            .as_deref()
345            .and_then(|t| parse_tz_spec_with_abbrevs(t, &settings.timezone_abbreviations))
346    });
347
348    let target_tz = settings
349        .to_timezone
350        .as_deref()
351        .and_then(|t| parse_tz_spec_with_abbrevs(t, &settings.timezone_abbreviations));
352
353    let want_aware = match settings.return_as_timezone_aware {
354        Some(flag) => flag,
355        None => extracted_tz.is_some(),
356    };
357
358    if let Some(tgt) = target_tz {
359        let utc_dt = match source_tz {
360            Some(TzSpec::Fixed(off)) => off
361                .from_local_datetime(&naive)
362                .single()
363                .map(|d| d.to_utc())
364                .unwrap_or_else(|| naive.and_utc()),
365            Some(TzSpec::Iana(tz)) => resolve_iana_local(tz, naive).to_utc(),
366            None => chrono::Local
367                .from_local_datetime(&naive)
368                .earliest()
369                .map(|d| d.to_utc())
370                .unwrap_or_else(|| naive.and_utc()),
371        };
372
373        return match tgt {
374            TzSpec::Fixed(off) => {
375                let converted = utc_dt.with_timezone(&off);
376                if want_aware {
377                    ParsedDateTime::FixedOffset(converted)
378                } else {
379                    ParsedDateTime::Naive(converted.naive_local())
380                }
381            }
382            TzSpec::Iana(tz) => {
383                let converted = utc_dt.with_timezone(&tz);
384                if want_aware {
385                    ParsedDateTime::Tz(converted)
386                } else {
387                    ParsedDateTime::Naive(converted.naive_local())
388                }
389            }
390        };
391    }
392
393    if want_aware {
394        match source_tz {
395            Some(TzSpec::Fixed(off)) => {
396                if let Some(dt) = off.from_local_datetime(&naive).single() {
397                    return ParsedDateTime::FixedOffset(dt);
398                }
399            }
400            Some(TzSpec::Iana(tz)) => {
401                return ParsedDateTime::Tz(resolve_iana_local(tz, naive));
402            }
403            None => {
404                if let Some(dt) = chrono::Local.from_local_datetime(&naive).earliest() {
405                    return ParsedDateTime::FixedOffset(dt.fixed_offset());
406                }
407            }
408        }
409    }
410
411    ParsedDateTime::Naive(naive)
412}