Skip to main content

dateoxide_core/
lib.rs

1//! High-performance, low-memory, zero-ReDoS multilingual natural-language date parser in pure Rust.
2//!
3//! `dateoxide-core` powers the Python package [`dateoxide`](https://pypi.org/project/dateoxide/)
4//! across 205 languages, non-Gregorian calendars (official Saudi Umm al-Qura Hijri,
5//! Jalali, Minguo, French Republican), time spans, and parallel batch parsing.
6//!
7//! # Quick Start
8//!
9//! ```
10//! use dateoxide_core::{calendars, parse, parse_batch, parse_with_settings, search::search_dates, settings::Settings};
11//! use chrono::{Datelike, NaiveDate, NaiveDateTime};
12//!
13//! // Fast ISO-8601, RFC-2822/3339, and ISO week date parsing
14//! let dt = parse("2026-11-26").unwrap();
15//! assert_eq!(dt.naive_local().date(), NaiveDate::from_ymd_opt(2026, 11, 26).unwrap());
16//!
17//! let iso_week = parse("2026-W48-4").unwrap();
18//! assert_eq!(iso_week.naive_local().date(), NaiveDate::from_ymd_opt(2026, 11, 26).unwrap());
19//!
20//! // Multilingual natural-language & relative parsing with fixed RELATIVE_BASE
21//! let mut settings = Settings::default();
22//! settings.relative_base = Some(
23//!     NaiveDateTime::parse_from_str("2026-11-26 15:00:00", "%Y-%m-%d %H:%M:%S").unwrap(),
24//! );
25//! let tr = parse_with_settings("3 gün önce", &settings).unwrap();
26//! assert_eq!(tr.naive_local().day(), 23);
27//!
28//! // Free-form text extraction and parallel batch parsing
29//! let found = search_dates("Meeting on 12 December 2025", &settings);
30//! assert_eq!(found.len(), 1);
31//!
32//! let batch = parse_batch(&["2026-11-26", "vor 2 Wochen", "not a date"], &settings);
33//! assert!(batch[0].is_some() && batch[1].is_some() && batch[2].is_none());
34//!
35//! // Non-Gregorian calendar conversion (official Umm al-Qura Hijri)
36//! let hijri = calendars::parse_hijri("1446/09/01", &settings);
37//! assert_eq!(hijri.date_obj.unwrap().naive_local().date(), NaiveDate::from_ymd_opt(2025, 3, 1).unwrap());
38//! ```
39
40pub mod absolute;
41#[cfg(feature = "calendars")]
42pub mod calendars;
43pub mod fast_path;
44pub mod locale;
45pub mod ranges;
46pub mod relative;
47pub mod search;
48pub mod settings;
49pub mod time_spans;
50pub mod timezone;
51#[cfg(feature = "calendars")]
52pub mod umm_al_qura;
53
54use locale::{normalize_digits_and_lower, LocaleRegistry};
55#[cfg(feature = "rayon")]
56use rayon::prelude::*;
57use search::SearchMatch;
58use settings::{DateData, ParsedDateTime, ParserKind, Period, Settings};
59use timezone::{extract_trailing_timezone_with_abbrevs, finalize_datetime};
60
61/// Parse a date string using default settings.
62#[inline]
63pub fn parse(input: &str) -> Option<ParsedDateTime> {
64    parse_with_settings(input, &Settings::default())
65}
66
67/// Parse a date string using explicit `Settings`.
68#[inline]
69pub fn parse_with_settings(input: &str, settings: &Settings) -> Option<ParsedDateTime> {
70    get_date_data(input, settings).date_obj
71}
72
73fn strip_user_skip_tokens(input: &str, skip_tokens: &[String]) -> String {
74    let mut out = Vec::new();
75    for tok in input.split_whitespace() {
76        let clean = tok.trim_matches(|c: char| c == ',' || c == '.');
77        if skip_tokens
78            .iter()
79            .any(|sk| sk.eq_ignore_ascii_case(tok) || sk.eq_ignore_ascii_case(clean))
80        {
81            continue;
82        }
83        out.push(tok);
84    }
85    out.join(" ")
86}
87
88#[inline]
89fn apply_time_period(period: Period, has_time: bool, settings: &Settings) -> Period {
90    if settings.return_time_as_period && has_time {
91        Period::Time
92    } else {
93        period
94    }
95}
96
97/// Relative-only parser backing `dateparser.freshness_date_parser.FreshnessDateDataParser`.
98pub fn parse_freshness(input: &str, settings: &Settings) -> DateData {
99    let trimmed = input.trim();
100    if trimmed.is_empty() {
101        return DateData::empty();
102    }
103    let (without_tz, tz) =
104        extract_trailing_timezone_with_abbrevs(trimmed, &settings.timezone_abbreviations);
105    let normalized = normalize_digits_and_lower(without_tz);
106    if normalized.is_empty() {
107        return DateData::empty();
108    }
109    let registry = LocaleRegistry::global();
110    let tokens: Vec<&str> = normalized
111        .split(|c: char| c.is_whitespace() || c == ',' || c == '/')
112        .map(|t| t.trim_matches(|c: char| c == '.' || c == '(' || c == ')'))
113        .filter(|t| !t.is_empty())
114        .collect();
115    let candidates = registry.detect_candidates(
116        &normalized,
117        &tokens,
118        settings.languages.as_deref(),
119        &settings.default_languages,
120        settings.normalize,
121        settings.use_given_language_order,
122    );
123    if let Some(m) = relative::try_parse_relative(&normalized, &candidates, registry, settings) {
124        return DateData {
125            date_obj: Some(finalize_datetime(m.naive, tz, settings)),
126            period: apply_time_period(m.period, m.has_time, settings),
127            locale: Some(m.locale),
128            parts: m.parts,
129            part_of_day: m.part_of_day,
130        };
131    }
132    DateData::empty()
133}
134
135#[inline]
136fn resolve_fast_path_locale(match_locale: Option<String>, settings: &Settings) -> String {
137    if let Some(loc) = match_locale {
138        return loc;
139    }
140    if let Some(first) = settings.languages.as_deref().and_then(|ls| ls.first()) {
141        let reg = LocaleRegistry::global();
142        if let Some(id) = reg.resolve_lang_id(first) {
143            return reg.locales[id].code.clone();
144        }
145    }
146    "en".to_string()
147}
148
149/// Full `dateparser.date.DateDataParser.get_date_data` equivalent returning
150/// `DateData { date_obj, period, locale, parts, part_of_day }`.
151pub fn get_date_data(input: &str, settings: &Settings) -> DateData {
152    let trimmed_raw = input.trim();
153    if trimmed_raw.is_empty() {
154        return DateData::empty();
155    }
156
157    let owned_cleaned;
158    let trimmed: &str = if settings.skip_tokens.is_empty() {
159        trimmed_raw
160    } else {
161        owned_cleaned = strip_user_skip_tokens(trimmed_raw, &settings.skip_tokens);
162        if owned_cleaned.trim().is_empty() {
163            return DateData::empty();
164        }
165        owned_cleaned.trim()
166    };
167
168    // 0. Custom user strptime formats (`date_formats`)
169    if let Some(m) = fast_path::try_custom_formats(trimmed, settings) {
170        return DateData {
171            date_obj: Some(finalize_datetime(m.naive, m.tz, settings)),
172            period: apply_time_period(m.period, m.has_time, settings),
173            locale: Some(resolve_fast_path_locale(m.locale, settings)),
174            parts: m.parts,
175            part_of_day: None,
176        };
177    }
178
179    // 1. Zero-regex, zero-allocation fast path
180    if let Some(m) = fast_path::try_fast_path(trimmed, settings) {
181        return DateData {
182            date_obj: Some(finalize_datetime(m.naive, m.tz, settings)),
183            period: apply_time_period(m.period, m.has_time, settings),
184            locale: Some(resolve_fast_path_locale(m.locale, settings)),
185            parts: m.parts,
186            part_of_day: None,
187        };
188    }
189
190    // 2. Peel off optional trailing timezone (or Unix ctime mid-string TZ) before normalization
191    let (without_tz_initial, mut tz) =
192        extract_trailing_timezone_with_abbrevs(trimmed, &settings.timezone_abbreviations);
193    let owned_embedded_tz;
194    let without_tz: &str = if tz.is_none() {
195        if let Some((cleaned, etz)) = timezone::extract_embedded_timezone_before_year(
196            without_tz_initial,
197            &settings.timezone_abbreviations,
198        ) {
199            tz = Some(etz);
200            owned_embedded_tz = cleaned;
201            &owned_embedded_tz
202        } else {
203            without_tz_initial
204        }
205    } else {
206        without_tz_initial
207    };
208    let normalized = normalize_digits_and_lower(without_tz);
209    if normalized.is_empty() {
210        return DateData::empty();
211    }
212
213    // Re-check fast path if Unicode digits (e.g. Arabic-Indic / Persian) were normalized to ASCII
214    if normalized.as_bytes()[0].is_ascii_digit() && normalized != without_tz {
215        if let Some(m) = fast_path::try_fast_path(&normalized, settings) {
216            return DateData {
217                date_obj: Some(finalize_datetime(m.naive, m.tz.or(tz), settings)),
218                period: apply_time_period(m.period, m.has_time, settings),
219                locale: Some(resolve_fast_path_locale(m.locale, settings)),
220                parts: m.parts,
221                part_of_day: None,
222            };
223        }
224    }
225
226    // 3. Lazy-load the compact 205-language registry and detect top candidates in O(tokens)
227    let registry = LocaleRegistry::global();
228    let mut tokens: Vec<&str> = Vec::with_capacity(8);
229    for chunk in normalized.split(|c: char| {
230        c.is_whitespace() || c == ',' || c == '/' || c == '[' || c == ']' || c == '–' || c == '—'
231    }) {
232        let clean = chunk.trim_matches(|c: char| matches!(c, '.' | '(' | ')' | '[' | ']'));
233        if clean.is_empty() {
234            continue;
235        }
236        if registry.token_to_langs.contains_key(clean) {
237            tokens.push(clean);
238            continue;
239        }
240        for sub in clean.split(['-', '.']) {
241            if sub.is_empty() {
242                continue;
243            }
244            if sub.chars().any(|c| c.is_ascii_digit()) && sub.chars().any(|c| c.is_alphabetic()) {
245                let mut start = 0usize;
246                let mut prev_d = sub.chars().next().unwrap().is_ascii_digit();
247                for (idx, ch) in sub.char_indices().skip(1) {
248                    let cur_d = ch.is_ascii_digit();
249                    if cur_d != prev_d {
250                        tokens.push(&sub[start..idx]);
251                        start = idx;
252                        prev_d = cur_d;
253                    }
254                }
255                if start < sub.len() {
256                    tokens.push(&sub[start..]);
257                }
258            } else {
259                tokens.push(sub);
260            }
261        }
262    }
263
264    let candidates = registry.detect_candidates(
265        &normalized,
266        &tokens,
267        settings.languages.as_deref(),
268        &settings.default_languages,
269        settings.normalize,
270        settings.use_given_language_order,
271    );
272
273    if candidates.is_empty() {
274        if settings.allows_parser(ParserKind::RelativeTime) {
275            if let Some(m) = relative::try_conversational_clock_or_fraction(&normalized, settings) {
276                return DateData {
277                    date_obj: Some(finalize_datetime(m.naive, tz, settings)),
278                    period: apply_time_period(m.period, m.has_time, settings),
279                    locale: Some(m.locale),
280                    parts: m.parts,
281                    part_of_day: m.part_of_day,
282                };
283            }
284        }
285        let is_cjk_or_bare_year = (normalized.len() == 4
286            && normalized.bytes().all(|b| b.is_ascii_digit()))
287            || normalized.contains('年')
288            || normalized.contains('月')
289            || normalized.contains('日')
290            || normalized.contains('년')
291            || normalized.contains('월')
292            || normalized.contains('일');
293        if settings.allows_parser(ParserKind::AbsoluteTime) && is_cjk_or_bare_year {
294            if let Some(m) = absolute::try_parse_absolute(&normalized, &[], registry, settings) {
295                return DateData {
296                    date_obj: Some(finalize_datetime(m.naive, tz, settings)),
297                    period: apply_time_period(m.period, m.has_time, settings),
298                    locale: Some(m.locale),
299                    parts: m.parts,
300                    part_of_day: m.part_of_day,
301                };
302            }
303        }
304        return ignore_surrounding_fallback(trimmed, settings);
305    }
306
307    // 4. Multilingual Relative Date Engine
308    if settings.allows_parser(ParserKind::RelativeTime) {
309        if let Some(m) = relative::try_parse_relative(&normalized, &candidates, registry, settings) {
310            return DateData {
311                date_obj: Some(finalize_datetime(m.naive, tz, settings)),
312                period: apply_time_period(m.period, m.has_time, settings),
313                locale: Some(m.locale),
314                parts: m.parts,
315                part_of_day: m.part_of_day,
316            };
317        }
318    }
319
320    // 5. Multilingual Absolute & Partial Date Engine
321    if settings.allows_parser(ParserKind::AbsoluteTime) {
322        if let Some(m) = absolute::try_parse_absolute(&normalized, &candidates, registry, settings) {
323            return DateData {
324                date_obj: Some(finalize_datetime(m.naive, tz, settings)),
325                period: apply_time_period(m.period, m.has_time, settings),
326                locale: Some(m.locale),
327                parts: m.parts,
328                part_of_day: m.part_of_day,
329            };
330        }
331    }
332
333    ignore_surrounding_fallback(trimmed, settings)
334}
335
336fn ignore_surrounding_fallback(trimmed: &str, settings: &Settings) -> DateData {
337    if !settings.ignore_surrounding_text {
338        return DateData::empty();
339    }
340    let mut inner = settings.clone();
341    inner.ignore_surrounding_text = false;
342    let found = search_dates_full(trimmed, &inner);
343    if let Some(first) = found.into_iter().next() {
344        return DateData {
345            date_obj: Some(first.date_obj),
346            period: first.period,
347            locale: first.locale,
348            parts: vec!["year", "month", "day"],
349            part_of_day: None,
350        };
351    }
352    DateData::empty()
353}
354
355/// Parallel batch parsing powered by Rayon across all available CPU cores
356/// (falls back to sequential iteration when the `rayon` feature is disabled).
357pub fn parse_batch<S: AsRef<str> + Sync>(
358    inputs: &[S],
359    settings: &Settings,
360) -> Vec<Option<ParsedDateTime>> {
361    #[cfg(feature = "rayon")]
362    {
363        if inputs.len() < 256 {
364            return inputs
365                .iter()
366                .map(|s| parse_with_settings(s.as_ref(), settings))
367                .collect();
368        }
369        return inputs
370            .par_iter()
371            .map(|s| parse_with_settings(s.as_ref(), settings))
372            .collect();
373    }
374    #[cfg(not(feature = "rayon"))]
375    {
376        inputs
377            .iter()
378            .map(|s| parse_with_settings(s.as_ref(), settings))
379            .collect()
380    }
381}
382
383/// Nullable parallel batch parsing (`Option<String>` inputs skip `None` cleanly).
384pub fn parse_batch_opt<S: AsRef<str> + Sync>(
385    inputs: &[Option<S>],
386    settings: &Settings,
387) -> Vec<Option<ParsedDateTime>> {
388    #[cfg(feature = "rayon")]
389    {
390        if inputs.len() < 256 {
391            return inputs
392                .iter()
393                .map(|opt| opt.as_ref().and_then(|s| parse_with_settings(s.as_ref(), settings)))
394                .collect();
395        }
396        return inputs
397            .par_iter()
398            .map(|opt| opt.as_ref().and_then(|s| parse_with_settings(s.as_ref(), settings)))
399            .collect();
400    }
401    #[cfg(not(feature = "rayon"))]
402    {
403        inputs
404            .iter()
405            .map(|opt| opt.as_ref().and_then(|s| parse_with_settings(s.as_ref(), settings)))
406            .collect()
407    }
408}
409
410/// Parse natural-language or numeric date/time ranges into `(start, end)`.
411pub fn parse_date_range(
412    input: &str,
413    settings: &Settings,
414) -> Option<(ParsedDateTime, ParsedDateTime)> {
415    ranges::parse_date_range(input, settings)
416}
417
418/// Find and parse all date expressions embedded in free-form text.
419pub fn search_dates(text: &str, settings: &Settings) -> Vec<(String, ParsedDateTime)> {
420    search::search_dates(text, settings)
421}
422
423/// Find and parse all date expressions embedded in free-form text, including detected locale code.
424pub fn search_dates_with_locale(
425    text: &str,
426    settings: &Settings,
427) -> Vec<(String, ParsedDateTime, Option<String>)> {
428    search::search_dates_with_locale(text, settings)
429}
430
431/// Find and parse all date expressions returning full match metadata.
432pub fn search_dates_full(text: &str, settings: &Settings) -> Vec<SearchMatch> {
433    search::search_dates_full(text, settings)
434}
435
436#[cfg(test)]
437mod tests {
438    use super::*;
439    use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike};
440    use settings::{DateOrder, PartOfDay, PreferDatesFrom, PreferDayOfMonth, StrictDateOrder};
441
442    fn fixed_settings() -> Settings {
443        Settings {
444            relative_base: Some(
445                NaiveDate::from_ymd_opt(2026, 11, 26)
446                    .unwrap()
447                    .and_hms_opt(15, 0, 0)
448                    .unwrap(),
449            ),
450            ..Default::default()
451        }
452    }
453
454    #[test]
455    fn test_fast_path_and_strict_date_order() {
456        let mut s = fixed_settings();
457        s.date_order = Some(DateOrder::MDY);
458        s.strict_date_order = StrictDateOrder::None;
459        assert_eq!(
460            parse_with_settings("26/11/2026", &s).unwrap().naive_local().date(),
461            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
462        );
463
464        s.strict_date_order = StrictDateOrder::All;
465        assert!(parse_with_settings("26/11/2026", &s).is_none());
466        assert_eq!(
467            parse_with_settings("2026/11/26", &s).unwrap().naive_local().date(),
468            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
469        );
470    }
471
472    #[cfg(feature = "calendars")]
473    #[test]
474    fn test_calendars_conversions() {
475        let s = fixed_settings();
476        assert_eq!(
477            calendars::jalali_to_gregorian(1395, 1, 1),
478            Some(NaiveDate::from_ymd_opt(2016, 3, 20).unwrap())
479        );
480        assert_eq!(
481            calendars::jalali_to_gregorian(1400, 1, 1),
482            Some(NaiveDate::from_ymd_opt(2021, 3, 21).unwrap())
483        );
484        assert_eq!(
485            calendars::jalali_to_gregorian(1404, 9, 5),
486            Some(NaiveDate::from_ymd_opt(2025, 11, 26).unwrap())
487        );
488        assert_eq!(
489            calendars::parse_jalali("۵ آذر ۱۴۰۴", &s).date_obj.unwrap().naive_local().date(),
490            NaiveDate::from_ymd_opt(2025, 11, 26).unwrap()
491        );
492
493        assert_eq!(
494            calendars::hijri_to_gregorian(1445, 1, 1),
495            Some(NaiveDate::from_ymd_opt(2023, 7, 19).unwrap())
496        );
497        assert_eq!(
498            calendars::hijri_to_gregorian(1446, 9, 1),
499            Some(NaiveDate::from_ymd_opt(2025, 3, 1).unwrap())
500        );
501
502        assert_eq!(
503            calendars::parse_minguo("115年11月26日", &s).date_obj.unwrap().naive_local().date(),
504            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
505        );
506
507        assert_eq!(
508            calendars::french_republican_to_gregorian(1, 1, 1),
509            Some(NaiveDate::from_ymd_opt(1792, 9, 22).unwrap())
510        );
511        assert_eq!(
512            calendars::parse_french_republican("14 Germinal an III", &s)
513                .date_obj
514                .unwrap()
515                .naive_local()
516                .date(),
517            NaiveDate::from_ymd_opt(1795, 4, 3).unwrap()
518        );
519    }
520
521    #[test]
522    fn test_parts_of_day_bare_durations_and_surrounding_text() {
523        let mut s = fixed_settings();
524        s.parts_of_day.morning = NaiveTime::from_hms_opt(8, 30, 0).unwrap();
525        let dd = get_date_data("yesterday morning", &s);
526        assert_eq!(
527            dd.date_obj.unwrap().naive_local(),
528            NaiveDate::from_ymd_opt(2026, 11, 25)
529                .unwrap()
530                .and_hms_opt(8, 30, 0)
531                .unwrap()
532        );
533        assert_eq!(dd.part_of_day, Some(PartOfDay::Morning));
534        assert_eq!(dd.parts, vec!["year", "month", "day", "time"]);
535
536        // Bare duration
537        let d_bare = parse_with_settings("2 days", &fixed_settings()).unwrap();
538        assert_eq!(d_bare.naive_local().date(), NaiveDate::from_ymd_opt(2026, 11, 24).unwrap());
539
540        // Week period
541        let dd_week = get_date_data("last week", &fixed_settings());
542        assert_eq!(dd_week.period, Period::Week);
543
544        // Ignore surrounding text
545        let mut s_ign = fixed_settings();
546        s_ign.ignore_surrounding_text = true;
547        assert_eq!(
548            parse_with_settings("Published: 12 December 2025", &s_ign)
549                .unwrap()
550                .naive_local()
551                .date(),
552            NaiveDate::from_ymd_opt(2025, 12, 12).unwrap()
553        );
554    }
555
556    #[test]
557    fn test_time_spans_and_custom_tz_abbrevs() {
558        let mut s = fixed_settings();
559        s.return_time_span = true;
560        let span_matches = search_dates_full("Show logs from last week please", &s);
561        assert_eq!(span_matches.len(), 2);
562
563        let mut s_tz = fixed_settings();
564        s_tz.timezone_abbreviations
565            .insert("FOO".to_string(), "+04:30".to_string());
566        s_tz.return_as_timezone_aware = Some(true);
567        let dt = parse_with_settings("2026-11-26 10:00 FOO", &s_tz).unwrap();
568        assert!(dt.is_aware());
569        assert_eq!(dt.naive_local().hour(), 10);
570    }
571
572    #[test]
573    fn test_timezone_conversion_and_preferences() {
574        let mut s = fixed_settings();
575        s.to_timezone = Some("Europe/Istanbul".to_string());
576        s.return_as_timezone_aware = Some(true);
577        let dt = parse_with_settings("2026-11-26T12:00:00Z", &s).unwrap();
578        assert_eq!(
579            dt.naive_local(),
580            NaiveDateTime::parse_from_str("2026-11-26 15:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
581        );
582
583        s.prefer_day_of_month = PreferDayOfMonth::First;
584        assert_eq!(
585            parse_with_settings("December 2025", &s).unwrap().naive_local().date(),
586            NaiveDate::from_ymd_opt(2025, 12, 1).unwrap()
587        );
588        s.prefer_dates_from = PreferDatesFrom::Past;
589        assert_eq!(
590            parse_with_settings("December 15", &s).unwrap().naive_local().date(),
591            NaiveDate::from_ymd_opt(2025, 12, 15).unwrap()
592        );
593    }
594
595    #[test]
596    fn test_iso_week_dates_and_year_zero_guard() {
597        let s = fixed_settings();
598        assert_eq!(
599            parse_with_settings("2026-W48-4", &s).unwrap().naive_local().date(),
600            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
601        );
602        assert_eq!(
603            parse_with_settings("2026-W48", &s).unwrap().naive_local().date(),
604            NaiveDate::from_ymd_opt(2026, 11, 23).unwrap()
605        );
606        assert_eq!(
607            parse_with_settings("2026W484", &s).unwrap().naive_local().date(),
608            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
609        );
610        assert!(parse_with_settings("2026-W54-1", &s).is_none());
611        assert!(parse_with_settings("0000-01-01", &s).is_none());
612
613        let mut s_strict = fixed_settings();
614        s_strict.strict_parsing = true;
615        assert!(parse_with_settings("2026-W48", &s_strict).is_none());
616    }
617
618    #[test]
619    fn test_no_spaces_time_and_time_only_preferences() {
620        let mut s_ns = fixed_settings();
621        s_ns.parsers = Some(vec![ParserKind::NoSpacesTime]);
622        assert_eq!(
623            parse_with_settings("1430", &s_ns).unwrap().naive_local(),
624            NaiveDate::from_ymd_opt(2026, 11, 26)
625                .unwrap()
626                .and_hms_opt(14, 30, 0)
627                .unwrap()
628        );
629        assert_eq!(
630            parse_with_settings("143025", &s_ns).unwrap().naive_local(),
631            NaiveDate::from_ymd_opt(2026, 11, 26)
632                .unwrap()
633                .and_hms_opt(14, 30, 25)
634                .unwrap()
635        );
636        s_ns.date_order = Some(DateOrder::DMY);
637        assert_eq!(
638            parse_with_settings("26112026", &s_ns).unwrap().naive_local().date(),
639            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
640        );
641        s_ns.date_order = Some(DateOrder::MDY);
642        assert_eq!(
643            parse_with_settings("11262026", &s_ns).unwrap().naive_local().date(),
644            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
645        );
646
647        let mut s_fut = fixed_settings();
648        s_fut.prefer_dates_from = PreferDatesFrom::Future;
649        assert_eq!(
650            parse_with_settings("09:00", &s_fut).unwrap().naive_local(),
651            NaiveDate::from_ymd_opt(2026, 11, 27)
652                .unwrap()
653                .and_hms_opt(9, 0, 0)
654                .unwrap()
655        );
656
657        let mut s_past = fixed_settings();
658        s_past.prefer_dates_from = PreferDatesFrom::Past;
659        assert_eq!(
660            parse_with_settings("18:00", &s_past).unwrap().naive_local(),
661            NaiveDate::from_ymd_opt(2026, 11, 25)
662                .unwrap()
663                .and_hms_opt(18, 0, 0)
664                .unwrap()
665        );
666    }
667
668    #[test]
669    fn test_search_dates_false_positive_guards() {
670        let s = fixed_settings();
671        let found = search_dates_full("Let us meet tomorrow at 5pm or next Friday.", &s);
672        assert!(!found.iter().any(|m| m.text == "Let"));
673        assert_eq!(found.len(), 2);
674
675        assert!(search_dates_full("She can see her man, did you say?", &s).is_empty());
676        assert!(search_dates_full("Python 3.12.1 on 192.168.1.1", &s).is_empty());
677    }
678
679    #[test]
680    fn test_v050_locale_region_date_order() {
681        let mut s_gb = fixed_settings();
682        s_gb.languages = Some(vec!["en-GB".to_string()]);
683        assert_eq!(
684            parse_with_settings("05/06/2026", &s_gb).unwrap().naive_local().date(),
685            NaiveDate::from_ymd_opt(2026, 6, 5).unwrap()
686        );
687
688        let mut s_us = fixed_settings();
689        s_us.languages = Some(vec!["en-US".to_string()]);
690        assert_eq!(
691            parse_with_settings("05/06/2026", &s_us).unwrap().naive_local().date(),
692            NaiveDate::from_ymd_opt(2026, 5, 6).unwrap()
693        );
694
695        let mut s_tr = fixed_settings();
696        s_tr.languages = Some(vec!["tr".to_string()]);
697        assert_eq!(
698            parse_with_settings("05/06/2026", &s_tr).unwrap().naive_local().date(),
699            NaiveDate::from_ymd_opt(2026, 6, 5).unwrap()
700        );
701
702        // Script subtag like "uz-Cyrl" must NOT be mistaken for a 2-letter region
703        assert_eq!(settings::extract_region_from_locale("uz-Cyrl"), None);
704        assert_eq!(settings::extract_region_from_locale("en-GB"), Some("GB"));
705        assert_eq!(settings::extract_region_from_locale("zh-Hans-TW"), Some("TW"));
706
707        // PREFER_LOCALE_DATE_ORDER = false falls back to MDY
708        let mut s_no_pref = fixed_settings();
709        s_no_pref.languages = Some(vec!["en-GB".to_string()]);
710        s_no_pref.prefer_locale_date_order = false;
711        assert_eq!(
712            parse_with_settings("05/06/2026", &s_no_pref).unwrap().naive_local().date(),
713            NaiveDate::from_ymd_opt(2026, 5, 6).unwrap()
714        );
715    }
716
717    #[test]
718    fn test_v050_apostrophe_year_japanese_eras_and_european_connectors() {
719        let s = fixed_settings();
720
721        // Apostrophe 2-digit years
722        assert_eq!(
723            parse_with_settings("Nov 26 '26", &s).unwrap().naive_local().date(),
724            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
725        );
726        assert_eq!(
727            parse_with_settings("15 Jan ’99", &s).unwrap().naive_local().date(),
728            NaiveDate::from_ymd_opt(1999, 1, 15).unwrap()
729        );
730        let nov_26 = get_date_data("Nov '26", &s);
731        assert_eq!(nov_26.period, Period::Month);
732        assert_eq!(nov_26.date_obj.as_ref().unwrap().naive_local().year(), 2026);
733        assert_eq!(nov_26.date_obj.as_ref().unwrap().naive_local().month(), 11);
734
735        // Japanese Imperial Eras
736        let reiwa = get_date_data("令和8年11月26日", &s);
737        assert_eq!(reiwa.locale.as_deref(), Some("ja"));
738        assert_eq!(
739            reiwa.date_obj.unwrap().naive_local().date(),
740            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
741        );
742        assert_eq!(
743            parse_with_settings("令和元年5月1日", &s).unwrap().naive_local().date(),
744            NaiveDate::from_ymd_opt(2019, 5, 1).unwrap()
745        );
746        assert_eq!(
747            parse_with_settings("平成31年4月30日", &s).unwrap().naive_local().date(),
748            NaiveDate::from_ymd_opt(2019, 4, 30).unwrap()
749        );
750        assert_eq!(
751            parse_with_settings("昭和64年1月7日", &s).unwrap().naive_local().date(),
752            NaiveDate::from_ymd_opt(1989, 1, 7).unwrap()
753        );
754        assert_eq!(
755            parse_with_settings("大正15年12月25日", &s).unwrap().naive_local().date(),
756            NaiveDate::from_ymd_opt(1926, 12, 25).unwrap()
757        );
758        assert_eq!(
759            parse_with_settings("明治45年7月30日", &s).unwrap().naive_local().date(),
760            NaiveDate::from_ymd_opt(1912, 7, 30).unwrap()
761        );
762        assert!(parse_with_settings("令和0年11月26日", &s).is_none());
763
764        // Italian & Spanish prepositions/connectors
765        let it_dt = get_date_data("il 15 gennaio 2026 alle 14:30", &s);
766        assert_eq!(it_dt.locale.as_deref(), Some("it"));
767        assert_eq!(
768            it_dt.date_obj.unwrap().naive_local(),
769            NaiveDate::from_ymd_opt(2026, 1, 15)
770                .unwrap()
771                .and_hms_opt(14, 30, 0)
772                .unwrap()
773        );
774        assert_eq!(
775            parse_with_settings("el 15 de enero de 2026 a las 14:30", &s)
776                .unwrap()
777                .naive_local(),
778            NaiveDate::from_ymd_opt(2026, 1, 15)
779                .unwrap()
780                .and_hms_opt(14, 30, 0)
781                .unwrap()
782        );
783    }
784
785    #[test]
786    fn test_v050_negative_timestamp_micros_and_localized_date_formats() {
787        let s = fixed_settings();
788        // Disabled by default
789        assert!(parse_with_settings("-86400", &s).is_none());
790
791        // Enabled explicitly via PARSERS=[NegativeTimestamp]
792        let mut s_neg = fixed_settings();
793        s_neg.parsers = Some(vec![ParserKind::NegativeTimestamp]);
794        assert_eq!(
795            parse_with_settings("-86400", &s_neg).unwrap().naive_local(),
796            NaiveDate::from_ymd_opt(1969, 12, 31)
797                .unwrap()
798                .and_hms_opt(0, 0, 0)
799                .unwrap()
800        );
801        assert_eq!(
802            parse_with_settings("-86400.5", &s_neg).unwrap().naive_local(),
803            NaiveDateTime::parse_from_str("1969-12-30 23:59:59.500", "%Y-%m-%d %H:%M:%S%.3f")
804                .unwrap()
805        );
806        assert!(parse_with_settings("-2026", &s_neg).is_none());
807
808        // 16-digit positive microsecond timestamp
809        assert_eq!(
810            parse_with_settings("1700000000123456", &s)
811                .unwrap()
812                .naive_local(),
813            DateTime::from_timestamp_micros(1700000000123456)
814                .unwrap()
815                .naive_utc()
816        );
817
818        // Localized strict custom date_formats (%B in Turkish & French)
819        let mut s_fmt = fixed_settings();
820        s_fmt.parsers = Some(vec![ParserKind::CustomFormats]);
821        s_fmt.date_formats = Some(vec!["%d %B %Y".to_string()]);
822        let tr_m = get_date_data("15 Ocak 2026", &s_fmt);
823        assert_eq!(tr_m.locale.as_deref(), Some("tr"));
824        assert_eq!(
825            tr_m.date_obj.unwrap().naive_local().date(),
826            NaiveDate::from_ymd_opt(2026, 1, 15).unwrap()
827        );
828        let fr_m = get_date_data("15 janvier 2026", &s_fmt);
829        assert_eq!(fr_m.locale.as_deref(), Some("fr"));
830        assert_eq!(
831            fr_m.date_obj.unwrap().naive_local().date(),
832            NaiveDate::from_ymd_opt(2026, 1, 15).unwrap()
833        );
834        assert!(parse_with_settings("15-01-2026", &s_fmt).is_none());
835    }
836
837    #[test]
838    fn test_v050_js_ctime_tz_world_abbrevs_and_parenthetical_guard() {
839        let s = fixed_settings();
840
841        // JavaScript Date.toString() formats with parenthesized TZ comments
842        let js1 = parse_with_settings("Thu Nov 26 2026 14:30:00 GMT+0300 (GMT+03:00)", &s).unwrap();
843        assert!(js1.is_aware());
844        assert_eq!(
845            js1.naive_local(),
846            NaiveDateTime::parse_from_str("2026-11-26 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
847        );
848        let js2 = parse_with_settings("Thu Nov 26 2026 14:30:00 GMT+0300 (Turkey Time)", &s).unwrap();
849        assert!(js2.is_aware());
850        assert_eq!(
851            js2.naive_local(),
852            NaiveDateTime::parse_from_str("2026-11-26 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
853        );
854        // Guard against arbitrary parenthesized text
855        assert!(parse_with_settings("Meeting (urgent)", &s).is_none());
856
857        // Unix ctime mid-string timezone before trailing 4-digit year
858        let ct1 = parse_with_settings("Thu Nov 26 14:30:00 UTC 2026", &s).unwrap();
859        assert!(ct1.is_aware());
860        assert_eq!(
861            ct1.naive_local(),
862            NaiveDateTime::parse_from_str("2026-11-26 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
863        );
864        let ct2 = parse_with_settings("Mon Jan 15 09:00:00 CEST 2026", &s).unwrap();
865        assert!(ct2.is_aware());
866        assert_eq!(
867            ct2.naive_local(),
868            NaiveDateTime::parse_from_str("2026-01-15 09:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
869        );
870
871        // Extended world timezone abbreviations + IST/BST backward-compat preserved
872        for tz_str in [
873            "15 Jan 2026 14:30 PKT",
874            "15 Jan 2026 14:30 WIB",
875            "15 Jan 2026 14:30 WITA",
876            "15 Jan 2026 14:30 WIT",
877            "15 Jan 2026 14:30 PHT",
878            "15 Jan 2026 14:30 NPT",
879            "15 Jan 2026 14:30 ACST",
880            "15 Jan 2026 14:30 ACDT",
881            "15 Jan 2026 14:30 CLT",
882            "15 Jan 2026 14:30 COT",
883            "15 Jan 2026 14:30 IRST",
884            "15 Jan 2026 14:30 AFT",
885            "15 Jan 2026 14:30 UZT",
886            "15 Jan 2026 14:30 ALMT",
887        ] {
888            let parsed = parse_with_settings(tz_str, &s).unwrap();
889            assert!(parsed.is_aware(), "expected aware for {}", tz_str);
890            assert_eq!(parsed.naive_local().hour(), 14);
891        }
892    }
893
894    #[test]
895    fn test_v050_no_spaces_12_14_prefixed_time_and_cjk_korean_relatives() {
896        let s = fixed_settings();
897
898        // 12/14-digit no-spaces-time gated behind PARSERS=[NoSpacesTime]
899        assert!(parse_with_settings("202601151430", &s).is_none());
900        let mut s_ns = fixed_settings();
901        s_ns.parsers = Some(vec![ParserKind::NoSpacesTime]);
902        assert_eq!(
903            parse_with_settings("202601151430", &s_ns).unwrap().naive_local(),
904            NaiveDateTime::parse_from_str("2026-01-15 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
905        );
906        assert_eq!(
907            parse_with_settings("20260115143045", &s_ns).unwrap().naive_local(),
908            NaiveDateTime::parse_from_str("2026-01-15 14:30:45", "%Y-%m-%d %H:%M:%S").unwrap()
909        );
910        s_ns.date_order = Some(DateOrder::DMY);
911        assert_eq!(
912            parse_with_settings("150120261430", &s_ns).unwrap().naive_local(),
913            NaiveDateTime::parse_from_str("2026-01-15 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
914        );
915
916        // "just now", "at 5:30 PM", "2026-11-26 t 14:30", "tomorrow at 5"
917        assert_eq!(
918            parse_with_settings("just now", &s).unwrap().naive_local(),
919            s.relative_base.unwrap()
920        );
921        assert_eq!(
922            parse_with_settings("at 5:30 PM", &s).unwrap().naive_local(),
923            NaiveDateTime::parse_from_str("2026-11-26 17:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
924        );
925        assert_eq!(
926            parse_with_settings("2026-11-26 t 14:30", &s).unwrap().naive_local(),
927            NaiveDateTime::parse_from_str("2026-11-26 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
928        );
929        assert_eq!(
930            parse_with_settings("tomorrow at 5", &s).unwrap().naive_local(),
931            NaiveDateTime::parse_from_str("2026-11-27 05:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
932        );
933
934        // Multi-unit attached & CJK/Korean relative+time
935        assert_eq!(
936            parse_with_settings("3日2時間前", &s).unwrap().naive_local(),
937            NaiveDateTime::parse_from_str("2026-11-23 13:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
938        );
939        assert_eq!(
940            parse_with_settings("昨日の14:30", &s).unwrap().naive_local(),
941            NaiveDateTime::parse_from_str("2026-11-25 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
942        );
943        assert_eq!(
944            parse_with_settings("昨日の午後2時30分", &s).unwrap().naive_local(),
945            NaiveDateTime::parse_from_str("2026-11-25 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
946        );
947        assert_eq!(
948            parse_with_settings("어제 오후 2시 30분", &s).unwrap().naive_local(),
949            NaiveDateTime::parse_from_str("2026-11-25 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
950        );
951        assert_eq!(
952            parse_with_settings("2일 3시간 전", &s).unwrap().naive_local(),
953            NaiveDateTime::parse_from_str("2026-11-24 12:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
954        );
955        assert_eq!(
956            parse_with_settings("1h30m ago", &s).unwrap().naive_local(),
957            NaiveDateTime::parse_from_str("2026-11-26 13:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
958        );
959    }
960
961    #[test]
962    fn test_v050_partial_formats_search_cjk_and_remaining_idioms() {
963        let s = fixed_settings();
964
965        // Partial date_formats
966        let mut s_fmt = fixed_settings();
967        s_fmt.parsers = Some(vec![ParserKind::CustomFormats]);
968        for (inp, fmt, exp) in [
969            ("November 2026", "%B %Y", "2026-11-26 00:00:00"),
970            ("2026-11", "%Y-%m", "2026-11-26 00:00:00"),
971            ("15 Ocak", "%d %B", "2026-01-15 00:00:00"),
972            ("14:30", "%H:%M", "2026-11-26 14:30:00"),
973            ("2026-330", "%Y-%j", "2026-11-26 00:00:00"),
974        ] {
975            s_fmt.date_formats = Some(vec![fmt.to_string()]);
976            assert_eq!(
977                parse_with_settings(inp, &s_fmt).unwrap().naive_local(),
978                NaiveDateTime::parse_from_str(exp, "%Y-%m-%d %H:%M:%S").unwrap(),
979                "failed partial custom format {} with {}",
980                inp,
981                fmt
982            );
983        }
984
985        // search_dates custom date_formats + precise CJK spans
986        let mut s_search_fmt = fixed_settings();
987        s_search_fmt.date_formats = Some(vec!["%Y_%m_%d".to_string()]);
988        let custom_found = search_dates_full("Release 2026_11_26 is live now.", &s_search_fmt);
989        assert_eq!(custom_found.len(), 2);
990        assert_eq!(custom_found[0].text, "2026_11_26");
991        assert_eq!(custom_found[1].text, "now");
992
993        let ja_found = search_dates_full("締め切りは2026年11月26日です。", &s);
994        assert_eq!(ja_found.len(), 1);
995        assert_eq!(ja_found[0].text, "2026年11月26日");
996
997        let zh_found = search_dates_full("会议定于2026年11月26日举行。", &s);
998        assert_eq!(zh_found.len(), 1);
999        assert_eq!(zh_found[0].text, "2026年11月26日");
1000
1001        let multi_cjk = search_dates_full("2026年11月20日から2026年11月26日まで", &s);
1002        assert_eq!(multi_cjk.len(), 2);
1003        assert_eq!(multi_cjk[0].text, "2026年11月20日");
1004        assert_eq!(multi_cjk[1].text, "2026年11月26日");
1005
1006        // Remaining 9 multilingual idioms + approx markers
1007        for (inp, exp) in [
1008            ("~3 days ago", "2026-11-23 15:00:00"),
1009            ("about 2 hours ago", "2026-11-26 13:00:00"),
1010            ("yaklaşık 2 saat önce", "2026-11-26 13:00:00"),
1011            ("約2時間前", "2026-11-26 13:00:00"),
1012            ("12 noon", "2026-11-26 12:00:00"),
1013            ("12 midnight", "2026-11-26 00:00:00"),
1014            ("next Monday morning", "2026-11-30 09:00:00"),
1015            ("через полчаса", "2026-11-26 15:30:00"),
1016            ("半小时前", "2026-11-26 14:30:00"),
1017            ("منذ يومين", "2026-11-24 15:00:00"),
1018            ("לפני שעתיים", "2026-11-26 13:00:00"),
1019        ] {
1020            assert_eq!(
1021                parse_with_settings(inp, &s).unwrap().naive_local(),
1022                NaiveDateTime::parse_from_str(exp, "%Y-%m-%d %H:%M:%S").unwrap(),
1023                "failed idiom {}",
1024                inp
1025            );
1026        }
1027    }
1028}