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::{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//! # #[cfg(feature = "calendars")]
36//! # {
37//! // Non-Gregorian calendar conversion (official Umm al-Qura Hijri)
38//! let hijri = dateoxide_core::calendars::parse_hijri("1446/09/01", &settings);
39//! assert_eq!(hijri.date_obj.unwrap().naive_local().date(), NaiveDate::from_ymd_opt(2025, 3, 1).unwrap());
40//! # }
41//! ```
42
43pub mod absolute;
44#[cfg(feature = "calendars")]
45pub mod calendars;
46pub mod fast_path;
47pub mod locale;
48pub mod nlp;
49pub mod numerals;
50pub mod ranges;
51pub mod relative;
52pub mod search;
53pub mod settings;
54pub mod time_spans;
55pub mod timezone;
56#[cfg(feature = "calendars")]
57pub mod umm_al_qura;
58
59use locale::{normalize_digits_and_lower, LocaleRegistry};
60#[cfg(feature = "rayon")]
61use rayon::prelude::*;
62use search::SearchMatch;
63use settings::{DateData, ParsedDateTime, ParserKind, Period, Settings};
64use timezone::{extract_trailing_timezone_with_abbrevs, finalize_datetime_checked};
65
66/// Parse a date string using default settings.
67#[inline]
68pub fn parse(input: &str) -> Option<ParsedDateTime> {
69    parse_with_settings(input, &Settings::default())
70}
71
72/// Parse a date string using explicit `Settings`.
73#[inline]
74pub fn parse_with_settings(input: &str, settings: &Settings) -> Option<ParsedDateTime> {
75    get_date_data(input, settings).date_obj
76}
77
78fn strip_user_skip_tokens(input: &str, skip_tokens: &[String]) -> String {
79    let mut out = Vec::new();
80    for tok in input.split_whitespace() {
81        let clean = tok.trim_matches(|c: char| c == ',' || c == '.');
82        if skip_tokens
83            .iter()
84            .any(|sk| sk.eq_ignore_ascii_case(tok) || sk.eq_ignore_ascii_case(clean))
85        {
86            continue;
87        }
88        out.push(tok);
89    }
90    out.join(" ")
91}
92
93#[inline]
94fn apply_time_period(period: Period, has_time: bool, settings: &Settings) -> Period {
95    if settings.return_time_as_period && has_time {
96        Period::Time
97    } else {
98        period
99    }
100}
101
102/// Relative-only parser backing `dateparser.freshness_date_parser.FreshnessDateDataParser`.
103pub fn parse_freshness(input: &str, settings: &Settings) -> DateData {
104    let trimmed = input.trim();
105    if trimmed.is_empty() {
106        return DateData::empty();
107    }
108    let (without_tz, tz) =
109        extract_trailing_timezone_with_abbrevs(trimmed, &settings.timezone_abbreviations);
110    let normalized = normalize_digits_and_lower(without_tz);
111    if normalized.is_empty() {
112        return DateData::empty();
113    }
114    let registry = LocaleRegistry::global();
115    let tokens: Vec<&str> = normalized
116        .split(|c: char| c.is_whitespace() || c == ',' || c == '/')
117        .map(|t| t.trim_matches(|c: char| c == '.' || c == '(' || c == ')'))
118        .filter(|t| !t.is_empty())
119        .collect();
120    let candidates = registry.detect_candidates(
121        &normalized,
122        &tokens,
123        settings.languages.as_deref(),
124        &settings.default_languages,
125        settings.normalize,
126        settings.use_given_language_order,
127    );
128    if let Some(m) = relative::try_parse_relative(&normalized, &candidates, registry, settings) {
129        let Some(dt) = finalize_datetime_checked(m.naive, tz, settings) else {
130            return DateData::empty();
131        };
132        return DateData {
133            date_obj: Some(dt),
134            period: apply_time_period(m.period, m.has_time, settings),
135            locale: Some(m.locale),
136            parts: m.parts,
137            part_of_day: m.part_of_day,
138        };
139    }
140    DateData::empty()
141}
142
143#[inline]
144fn resolve_fast_path_locale(match_locale: Option<String>, settings: &Settings) -> String {
145    if let Some(loc) = match_locale {
146        return loc;
147    }
148    if let Some(first) = settings.languages.as_deref().and_then(|ls| ls.first()) {
149        let reg = LocaleRegistry::global();
150        if let Some(id) = reg.resolve_lang_id(first) {
151            return reg.locales[id].code.clone();
152        }
153    }
154    "en".to_string()
155}
156
157#[allow(clippy::too_many_arguments)]
158#[inline]
159fn build_datedata(
160    naive: chrono::NaiveDateTime,
161    tz: Option<timezone::TzSpec>,
162    period: Period,
163    has_time: bool,
164    locale: String,
165    parts: Vec<&'static str>,
166    part_of_day: Option<settings::PartOfDay>,
167    settings: &Settings,
168) -> DateData {
169    let Some(dt) = finalize_datetime_checked(naive, tz, settings) else {
170        return DateData::empty();
171    };
172    DateData {
173        date_obj: Some(dt),
174        period: apply_time_period(period, has_time, settings),
175        locale: Some(locale),
176        parts,
177        part_of_day,
178    }
179}
180
181/// Full `dateparser.date.DateDataParser.get_date_data` equivalent returning
182/// `DateData { date_obj, period, locale, parts, part_of_day }`.
183pub fn get_date_data(input: &str, settings: &Settings) -> DateData {
184    let trimmed_raw = input.trim();
185    if trimmed_raw.is_empty() || trimmed_raw.contains('\0') {
186        return DateData::empty();
187    }
188
189    let owned_cleaned;
190    let skip_trimmed: &str = if settings.skip_tokens.is_empty() {
191        trimmed_raw
192    } else {
193        owned_cleaned = strip_user_skip_tokens(trimmed_raw, &settings.skip_tokens);
194        if owned_cleaned.trim().is_empty() {
195            return DateData::empty();
196        }
197        owned_cleaned.trim()
198    };
199
200    let unicode_cleaned = locale::clean_unicode_surface(skip_trimmed);
201    let trimmed = unicode_cleaned.as_ref();
202    if trimmed.is_empty() {
203        return DateData::empty();
204    }
205
206    // Currency-amount guard in auto-detect mode (e.g. "25 EUR", "EUR 2026", "100 SEK", "50 NGN")
207    if settings.languages.is_none() {
208        let mut parts = trimmed.split_whitespace();
209        if let (Some(a_tok), Some(b_tok), None) = (parts.next(), parts.next(), parts.next()) {
210            let is_cur_num = |num_tok: &str, cur_tok: &str| {
211                let n_clean = num_tok.trim_matches(|c: char| matches!(c, '+' | '-'));
212                !n_clean.is_empty()
213                    && n_clean.bytes().all(|b| b.is_ascii_digit() || b == b'.' || b == b',')
214                    && locale::is_iso4217_currency(cur_tok)
215            };
216            if is_cur_num(a_tok, b_tok) || is_cur_num(b_tok, a_tok) {
217                return DateData::empty();
218            }
219        }
220    }
221
222    // 0. Custom user strptime formats (`date_formats`)
223    if let Some(m) = fast_path::try_custom_formats(trimmed, settings) {
224        return build_datedata(
225            m.naive,
226            m.tz,
227            m.period,
228            m.has_time,
229            resolve_fast_path_locale(m.locale, settings),
230            m.parts,
231            None,
232            settings,
233        );
234    }
235
236    // 1. Zero-regex, zero-allocation fast path
237    if let Some(m) = fast_path::try_fast_path(trimmed, settings) {
238        return build_datedata(
239            m.naive,
240            m.tz,
241            m.period,
242            m.has_time,
243            resolve_fast_path_locale(m.locale, settings),
244            m.parts,
245            None,
246            settings,
247        );
248    }
249
250    // 2. Peel off optional trailing timezone (or Unix ctime mid-string TZ) before normalization
251    let (without_tz_initial, mut tz) =
252        extract_trailing_timezone_with_abbrevs(trimmed, &settings.timezone_abbreviations);
253    let owned_embedded_tz;
254    let without_tz: &str = if tz.is_none() {
255        if let Some((cleaned, etz)) = timezone::extract_embedded_timezone_before_year(
256            without_tz_initial,
257            &settings.timezone_abbreviations,
258        ) {
259            tz = Some(etz);
260            owned_embedded_tz = cleaned;
261            &owned_embedded_tz
262        } else {
263            without_tz_initial
264        }
265    } else {
266        without_tz_initial
267    };
268    let norm_nd = normalize_digits_and_lower(without_tz);
269    if norm_nd.is_empty() {
270        return DateData::empty();
271    }
272    let norm_script = numerals::normalize_non_decimal_numerals(&norm_nd);
273    let normalized = norm_script.as_ref();
274
275    // Re-check fast path if Unicode digits (e.g. Arabic-Indic / Persian / all 68 Nd scripts) were normalized to ASCII
276    if normalized.as_bytes()[0].is_ascii_digit() && normalized != without_tz {
277        if let Some(m) = fast_path::try_fast_path(normalized, settings) {
278            return build_datedata(
279                m.naive,
280                m.tz.or(tz),
281                m.period,
282                m.has_time,
283                resolve_fast_path_locale(m.locale, settings),
284                m.parts,
285                None,
286                settings,
287            );
288        }
289    }
290
291    // Conversational NLP engine (period boundaries, quarters, seasons, business days, chained relatives, clocks)
292    match nlp::try_parse_nlp(normalized, settings) {
293        nlp::NlpOutcome::Matched(m) => {
294            return build_datedata(
295                m.naive,
296                tz,
297                m.period,
298                m.has_time,
299                m.locale,
300                m.parts,
301                m.part_of_day,
302                settings,
303            );
304        }
305        nlp::NlpOutcome::Invalid => return DateData::empty(),
306        nlp::NlpOutcome::NoMatch => {}
307    }
308
309    // 3. Lazy-load the compact 205-language registry and detect top candidates in O(tokens)
310    let registry = LocaleRegistry::global();
311    let mut tokens: Vec<&str> = Vec::with_capacity(8);
312    for chunk in normalized.split(|c: char| {
313        c.is_whitespace() || c == ',' || c == '/' || c == '[' || c == ']' || c == '–' || c == '—'
314    }) {
315        let clean = chunk.trim_matches(|c: char| matches!(c, '.' | '(' | ')' | '[' | ']'));
316        if clean.is_empty() {
317            continue;
318        }
319        if registry.token_to_langs.contains_key(clean) {
320            tokens.push(clean);
321            continue;
322        }
323        for sub in clean.split(['-', '.']) {
324            if sub.is_empty() {
325                continue;
326            }
327            if sub.chars().any(|c| c.is_ascii_digit()) && sub.chars().any(|c| c.is_alphabetic()) {
328                let mut start = 0usize;
329                let mut prev_d = sub.chars().next().unwrap().is_ascii_digit();
330                for (idx, ch) in sub.char_indices().skip(1) {
331                    let cur_d = ch.is_ascii_digit();
332                    if cur_d != prev_d {
333                        tokens.push(&sub[start..idx]);
334                        start = idx;
335                        prev_d = cur_d;
336                    }
337                }
338                if start < sub.len() {
339                    tokens.push(&sub[start..]);
340                }
341            } else {
342                tokens.push(sub);
343            }
344        }
345    }
346
347    let candidates = registry.detect_candidates(
348        normalized,
349        &tokens,
350        settings.languages.as_deref(),
351        &settings.default_languages,
352        settings.normalize,
353        settings.use_given_language_order,
354    );
355
356    if candidates.is_empty() {
357        if settings.allows_parser(ParserKind::RelativeTime) {
358            if let Some(m) = relative::try_conversational_clock_or_fraction(normalized, settings) {
359                return build_datedata(
360                    m.naive,
361                    tz,
362                    m.period,
363                    m.has_time,
364                    m.locale,
365                    m.parts,
366                    m.part_of_day,
367                    settings,
368                );
369            }
370        }
371        let is_cjk_or_bare_year = (normalized.len() == 4
372            && normalized.bytes().all(|b| b.is_ascii_digit()))
373            || normalized.contains('年')
374            || normalized.contains('月')
375            || normalized.contains('日')
376            || normalized.contains('년')
377            || normalized.contains('월')
378            || normalized.contains('일');
379        let roman_part_count = trimmed
380            .split(|c: char| !c.is_ascii_alphanumeric())
381            .filter(|t| !t.is_empty())
382            .count();
383        let has_roman_month_cand = roman_part_count >= 2
384            && trimmed
385                .split(|c: char| !c.is_ascii_alphanumeric())
386                .any(|t| {
387                    !t.is_empty()
388                        && t.len() <= 15
389                        && t.bytes().all(|b| b.is_ascii_uppercase())
390                        && numerals::parse_roman_numeral(t).is_some()
391                });
392        if settings.allows_parser(ParserKind::AbsoluteTime) && (is_cjk_or_bare_year || has_roman_month_cand) {
393            let fallback_cands: Vec<usize> = if has_roman_month_cand {
394                registry.resolve_lang_id("en").into_iter().collect()
395            } else {
396                Vec::new()
397            };
398            if let Some(m) = absolute::try_parse_absolute_with_raw(
399                normalized,
400                Some(trimmed),
401                &fallback_cands,
402                registry,
403                settings,
404            ) {
405                return build_datedata(
406                    m.naive,
407                    tz,
408                    m.period,
409                    m.has_time,
410                    m.locale,
411                    m.parts,
412                    m.part_of_day,
413                    settings,
414                );
415            }
416        }
417        return ignore_surrounding_fallback(trimmed, settings);
418    }
419
420    // 4. Multilingual Relative Date Engine
421    if settings.allows_parser(ParserKind::RelativeTime) {
422        match relative::try_parse_relative_outcome(normalized, &candidates, registry, settings) {
423            relative::RelativeOutcome::Matched(m) => {
424                return build_datedata(
425                    m.naive,
426                    tz,
427                    m.period,
428                    m.has_time,
429                    m.locale,
430                    m.parts,
431                    m.part_of_day,
432                    settings,
433                );
434            }
435            relative::RelativeOutcome::OutOfBounds => return DateData::empty(),
436            relative::RelativeOutcome::NoMatch => {}
437        }
438    }
439
440    // 5. Multilingual Absolute & Partial Date Engine
441    if settings.allows_parser(ParserKind::AbsoluteTime) {
442        if let Some(m) =
443            absolute::try_parse_absolute_with_raw(normalized, Some(trimmed), &candidates, registry, settings)
444        {
445            return build_datedata(
446                m.naive,
447                tz,
448                m.period,
449                m.has_time,
450                m.locale,
451                m.parts,
452                m.part_of_day,
453                settings,
454            );
455        }
456    }
457
458    ignore_surrounding_fallback(trimmed, settings)
459}
460
461fn ignore_surrounding_fallback(trimmed: &str, settings: &Settings) -> DateData {
462    if !settings.ignore_surrounding_text {
463        return DateData::empty();
464    }
465    let mut inner = settings.clone();
466    inner.ignore_surrounding_text = false;
467    let found = search_dates_full(trimmed, &inner);
468    if let Some(first) = found.into_iter().next() {
469        return DateData {
470            date_obj: Some(first.date_obj),
471            period: first.period,
472            locale: first.locale,
473            parts: first.parts,
474            part_of_day: first.part_of_day,
475        };
476    }
477    DateData::empty()
478}
479
480/// Parallel batch parsing powered by Rayon across all available CPU cores
481/// (falls back to sequential iteration when the `rayon` feature is disabled).
482pub fn parse_batch<S: AsRef<str> + Sync>(
483    inputs: &[S],
484    settings: &Settings,
485) -> Vec<Option<ParsedDateTime>> {
486    #[cfg(feature = "rayon")]
487    {
488        if inputs.len() < 256 {
489            return inputs
490                .iter()
491                .map(|s| parse_with_settings(s.as_ref(), settings))
492                .collect();
493        }
494        inputs
495            .par_iter()
496            .map(|s| parse_with_settings(s.as_ref(), settings))
497            .collect()
498    }
499    #[cfg(not(feature = "rayon"))]
500    {
501        inputs
502            .iter()
503            .map(|s| parse_with_settings(s.as_ref(), settings))
504            .collect()
505    }
506}
507
508/// Nullable parallel batch parsing (`Option<String>` inputs skip `None` cleanly).
509pub fn parse_batch_opt<S: AsRef<str> + Sync>(
510    inputs: &[Option<S>],
511    settings: &Settings,
512) -> Vec<Option<ParsedDateTime>> {
513    #[cfg(feature = "rayon")]
514    {
515        if inputs.len() < 256 {
516            return inputs
517                .iter()
518                .map(|opt| opt.as_ref().and_then(|s| parse_with_settings(s.as_ref(), settings)))
519                .collect();
520        }
521        inputs
522            .par_iter()
523            .map(|opt| opt.as_ref().and_then(|s| parse_with_settings(s.as_ref(), settings)))
524            .collect()
525    }
526    #[cfg(not(feature = "rayon"))]
527    {
528        inputs
529            .iter()
530            .map(|opt| opt.as_ref().and_then(|s| parse_with_settings(s.as_ref(), settings)))
531            .collect()
532    }
533}
534
535/// Parse natural-language or numeric date/time ranges into `(start, end)`.
536pub fn parse_date_range(
537    input: &str,
538    settings: &Settings,
539) -> Option<(ParsedDateTime, ParsedDateTime)> {
540    ranges::parse_date_range(input, settings)
541}
542
543/// Find and parse all date expressions embedded in free-form text.
544pub fn search_dates(text: &str, settings: &Settings) -> Vec<(String, ParsedDateTime)> {
545    search::search_dates(text, settings)
546}
547
548/// Find and parse all date expressions embedded in free-form text, including detected locale code.
549pub fn search_dates_with_locale(
550    text: &str,
551    settings: &Settings,
552) -> Vec<(String, ParsedDateTime, Option<String>)> {
553    search::search_dates_with_locale(text, settings)
554}
555
556/// Find and parse all date expressions returning full match metadata.
557pub fn search_dates_full(text: &str, settings: &Settings) -> Vec<SearchMatch> {
558    search::search_dates_full(text, settings)
559}
560
561#[cfg(test)]
562mod tests {
563    use super::*;
564    use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike};
565    use settings::{DateOrder, PartOfDay, PreferDatesFrom, PreferDayOfMonth, StrictDateOrder};
566
567    fn fixed_settings() -> Settings {
568        Settings {
569            relative_base: Some(
570                NaiveDate::from_ymd_opt(2026, 11, 26)
571                    .unwrap()
572                    .and_hms_opt(15, 0, 0)
573                    .unwrap(),
574            ),
575            ..Default::default()
576        }
577    }
578
579    #[test]
580    fn test_fast_path_and_strict_date_order() {
581        let mut s = fixed_settings();
582        s.date_order = Some(DateOrder::MDY);
583        s.strict_date_order = StrictDateOrder::None;
584        assert_eq!(
585            parse_with_settings("26/11/2026", &s).unwrap().naive_local().date(),
586            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
587        );
588
589        s.strict_date_order = StrictDateOrder::All;
590        assert!(parse_with_settings("26/11/2026", &s).is_none());
591        assert_eq!(
592            parse_with_settings("2026/11/26", &s).unwrap().naive_local().date(),
593            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
594        );
595    }
596
597    #[cfg(feature = "calendars")]
598    #[test]
599    fn test_calendars_conversions() {
600        let s = fixed_settings();
601        assert_eq!(
602            calendars::jalali_to_gregorian(1395, 1, 1),
603            Some(NaiveDate::from_ymd_opt(2016, 3, 20).unwrap())
604        );
605        assert_eq!(
606            calendars::jalali_to_gregorian(1400, 1, 1),
607            Some(NaiveDate::from_ymd_opt(2021, 3, 21).unwrap())
608        );
609        assert_eq!(
610            calendars::jalali_to_gregorian(1404, 9, 5),
611            Some(NaiveDate::from_ymd_opt(2025, 11, 26).unwrap())
612        );
613        assert_eq!(
614            calendars::parse_jalali("۵ آذر ۱۴۰۴", &s).date_obj.unwrap().naive_local().date(),
615            NaiveDate::from_ymd_opt(2025, 11, 26).unwrap()
616        );
617
618        assert_eq!(
619            calendars::hijri_to_gregorian(1445, 1, 1),
620            Some(NaiveDate::from_ymd_opt(2023, 7, 19).unwrap())
621        );
622        assert_eq!(
623            calendars::hijri_to_gregorian(1446, 9, 1),
624            Some(NaiveDate::from_ymd_opt(2025, 3, 1).unwrap())
625        );
626
627        assert_eq!(
628            calendars::parse_minguo("115年11月26日", &s).date_obj.unwrap().naive_local().date(),
629            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
630        );
631
632        assert_eq!(
633            calendars::french_republican_to_gregorian(1, 1, 1),
634            Some(NaiveDate::from_ymd_opt(1792, 9, 22).unwrap())
635        );
636        assert_eq!(
637            calendars::parse_french_republican("14 Germinal an III", &s)
638                .date_obj
639                .unwrap()
640                .naive_local()
641                .date(),
642            NaiveDate::from_ymd_opt(1795, 4, 3).unwrap()
643        );
644    }
645
646    #[test]
647    fn test_parts_of_day_bare_durations_and_surrounding_text() {
648        let mut s = fixed_settings();
649        s.parts_of_day.morning = NaiveTime::from_hms_opt(8, 30, 0).unwrap();
650        let dd = get_date_data("yesterday morning", &s);
651        assert_eq!(
652            dd.date_obj.unwrap().naive_local(),
653            NaiveDate::from_ymd_opt(2026, 11, 25)
654                .unwrap()
655                .and_hms_opt(8, 30, 0)
656                .unwrap()
657        );
658        assert_eq!(dd.part_of_day, Some(PartOfDay::Morning));
659        assert_eq!(dd.parts, vec!["year", "month", "day", "time"]);
660
661        // Bare duration
662        let d_bare = parse_with_settings("2 days", &fixed_settings()).unwrap();
663        assert_eq!(d_bare.naive_local().date(), NaiveDate::from_ymd_opt(2026, 11, 24).unwrap());
664
665        // Week period
666        let dd_week = get_date_data("last week", &fixed_settings());
667        assert_eq!(dd_week.period, Period::Week);
668
669        // Ignore surrounding text
670        let mut s_ign = fixed_settings();
671        s_ign.ignore_surrounding_text = true;
672        assert_eq!(
673            parse_with_settings("Published: 12 December 2025", &s_ign)
674                .unwrap()
675                .naive_local()
676                .date(),
677            NaiveDate::from_ymd_opt(2025, 12, 12).unwrap()
678        );
679    }
680
681    #[test]
682    fn test_time_spans_and_custom_tz_abbrevs() {
683        let mut s = fixed_settings();
684        s.return_time_span = true;
685        let span_matches = search_dates_full("Show logs from last week please", &s);
686        assert_eq!(span_matches.len(), 2);
687
688        let mut s_tz = fixed_settings();
689        s_tz.timezone_abbreviations
690            .insert("FOO".to_string(), "+04:30".to_string());
691        s_tz.return_as_timezone_aware = Some(true);
692        let dt = parse_with_settings("2026-11-26 10:00 FOO", &s_tz).unwrap();
693        assert!(dt.is_aware());
694        assert_eq!(dt.naive_local().hour(), 10);
695    }
696
697    #[test]
698    fn test_timezone_conversion_and_preferences() {
699        let mut s = fixed_settings();
700        s.to_timezone = Some("Europe/Istanbul".to_string());
701        s.return_as_timezone_aware = Some(true);
702        let dt = parse_with_settings("2026-11-26T12:00:00Z", &s).unwrap();
703        assert_eq!(
704            dt.naive_local(),
705            NaiveDateTime::parse_from_str("2026-11-26 15:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
706        );
707
708        s.prefer_day_of_month = PreferDayOfMonth::First;
709        assert_eq!(
710            parse_with_settings("December 2025", &s).unwrap().naive_local().date(),
711            NaiveDate::from_ymd_opt(2025, 12, 1).unwrap()
712        );
713        s.prefer_dates_from = PreferDatesFrom::Past;
714        assert_eq!(
715            parse_with_settings("December 15", &s).unwrap().naive_local().date(),
716            NaiveDate::from_ymd_opt(2025, 12, 15).unwrap()
717        );
718    }
719
720    #[test]
721    fn test_iso_week_dates_and_year_zero_guard() {
722        let s = fixed_settings();
723        assert_eq!(
724            parse_with_settings("2026-W48-4", &s).unwrap().naive_local().date(),
725            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
726        );
727        assert_eq!(
728            parse_with_settings("2026-W48", &s).unwrap().naive_local().date(),
729            NaiveDate::from_ymd_opt(2026, 11, 23).unwrap()
730        );
731        assert_eq!(
732            parse_with_settings("2026W484", &s).unwrap().naive_local().date(),
733            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
734        );
735        assert!(parse_with_settings("2026-W54-1", &s).is_none());
736        assert!(parse_with_settings("0000-01-01", &s).is_none());
737
738        let mut s_strict = fixed_settings();
739        s_strict.strict_parsing = true;
740        assert!(parse_with_settings("2026-W48", &s_strict).is_none());
741    }
742
743    #[test]
744    fn test_no_spaces_time_and_time_only_preferences() {
745        let mut s_ns = fixed_settings();
746        s_ns.parsers = Some(vec![ParserKind::NoSpacesTime]);
747        assert_eq!(
748            parse_with_settings("1430", &s_ns).unwrap().naive_local(),
749            NaiveDate::from_ymd_opt(2026, 11, 26)
750                .unwrap()
751                .and_hms_opt(14, 30, 0)
752                .unwrap()
753        );
754        assert_eq!(
755            parse_with_settings("143025", &s_ns).unwrap().naive_local(),
756            NaiveDate::from_ymd_opt(2026, 11, 26)
757                .unwrap()
758                .and_hms_opt(14, 30, 25)
759                .unwrap()
760        );
761        s_ns.date_order = Some(DateOrder::DMY);
762        assert_eq!(
763            parse_with_settings("26112026", &s_ns).unwrap().naive_local().date(),
764            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
765        );
766        s_ns.date_order = Some(DateOrder::MDY);
767        assert_eq!(
768            parse_with_settings("11262026", &s_ns).unwrap().naive_local().date(),
769            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
770        );
771
772        let mut s_fut = fixed_settings();
773        s_fut.prefer_dates_from = PreferDatesFrom::Future;
774        assert_eq!(
775            parse_with_settings("09:00", &s_fut).unwrap().naive_local(),
776            NaiveDate::from_ymd_opt(2026, 11, 27)
777                .unwrap()
778                .and_hms_opt(9, 0, 0)
779                .unwrap()
780        );
781
782        let mut s_past = fixed_settings();
783        s_past.prefer_dates_from = PreferDatesFrom::Past;
784        assert_eq!(
785            parse_with_settings("18:00", &s_past).unwrap().naive_local(),
786            NaiveDate::from_ymd_opt(2026, 11, 25)
787                .unwrap()
788                .and_hms_opt(18, 0, 0)
789                .unwrap()
790        );
791    }
792
793    #[test]
794    fn test_search_dates_false_positive_guards() {
795        let s = fixed_settings();
796        let found = search_dates_full("Let us meet tomorrow at 5pm or next Friday.", &s);
797        assert!(!found.iter().any(|m| m.text == "Let"));
798        assert_eq!(found.len(), 2);
799
800        assert!(search_dates_full("She can see her man, did you say?", &s).is_empty());
801        assert!(search_dates_full("Python 3.12.1 on 192.168.1.1", &s).is_empty());
802    }
803
804    #[test]
805    fn test_v050_locale_region_date_order() {
806        let mut s_gb = fixed_settings();
807        s_gb.languages = Some(vec!["en-GB".to_string()]);
808        assert_eq!(
809            parse_with_settings("05/06/2026", &s_gb).unwrap().naive_local().date(),
810            NaiveDate::from_ymd_opt(2026, 6, 5).unwrap()
811        );
812
813        let mut s_us = fixed_settings();
814        s_us.languages = Some(vec!["en-US".to_string()]);
815        assert_eq!(
816            parse_with_settings("05/06/2026", &s_us).unwrap().naive_local().date(),
817            NaiveDate::from_ymd_opt(2026, 5, 6).unwrap()
818        );
819
820        let mut s_tr = fixed_settings();
821        s_tr.languages = Some(vec!["tr".to_string()]);
822        assert_eq!(
823            parse_with_settings("05/06/2026", &s_tr).unwrap().naive_local().date(),
824            NaiveDate::from_ymd_opt(2026, 6, 5).unwrap()
825        );
826
827        // Script subtag like "uz-Cyrl" must NOT be mistaken for a 2-letter region
828        assert_eq!(settings::extract_region_from_locale("uz-Cyrl"), None);
829        assert_eq!(settings::extract_region_from_locale("en-GB"), Some("GB"));
830        assert_eq!(settings::extract_region_from_locale("zh-Hans-TW"), Some("TW"));
831
832        // PREFER_LOCALE_DATE_ORDER = false falls back to MDY
833        let mut s_no_pref = fixed_settings();
834        s_no_pref.languages = Some(vec!["en-GB".to_string()]);
835        s_no_pref.prefer_locale_date_order = false;
836        assert_eq!(
837            parse_with_settings("05/06/2026", &s_no_pref).unwrap().naive_local().date(),
838            NaiveDate::from_ymd_opt(2026, 5, 6).unwrap()
839        );
840    }
841
842    #[test]
843    fn test_v050_apostrophe_year_japanese_eras_and_european_connectors() {
844        let s = fixed_settings();
845
846        // Apostrophe 2-digit years
847        assert_eq!(
848            parse_with_settings("Nov 26 '26", &s).unwrap().naive_local().date(),
849            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
850        );
851        assert_eq!(
852            parse_with_settings("15 Jan ’99", &s).unwrap().naive_local().date(),
853            NaiveDate::from_ymd_opt(1999, 1, 15).unwrap()
854        );
855        let nov_26 = get_date_data("Nov '26", &s);
856        assert_eq!(nov_26.period, Period::Month);
857        assert_eq!(nov_26.date_obj.as_ref().unwrap().naive_local().year(), 2026);
858        assert_eq!(nov_26.date_obj.as_ref().unwrap().naive_local().month(), 11);
859
860        // Japanese Imperial Eras
861        let reiwa = get_date_data("令和8年11月26日", &s);
862        assert_eq!(reiwa.locale.as_deref(), Some("ja"));
863        assert_eq!(
864            reiwa.date_obj.unwrap().naive_local().date(),
865            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
866        );
867        assert_eq!(
868            parse_with_settings("令和元年5月1日", &s).unwrap().naive_local().date(),
869            NaiveDate::from_ymd_opt(2019, 5, 1).unwrap()
870        );
871        assert_eq!(
872            parse_with_settings("平成31年4月30日", &s).unwrap().naive_local().date(),
873            NaiveDate::from_ymd_opt(2019, 4, 30).unwrap()
874        );
875        assert_eq!(
876            parse_with_settings("昭和64年1月7日", &s).unwrap().naive_local().date(),
877            NaiveDate::from_ymd_opt(1989, 1, 7).unwrap()
878        );
879        assert_eq!(
880            parse_with_settings("大正15年12月25日", &s).unwrap().naive_local().date(),
881            NaiveDate::from_ymd_opt(1926, 12, 25).unwrap()
882        );
883        assert_eq!(
884            parse_with_settings("明治45年7月30日", &s).unwrap().naive_local().date(),
885            NaiveDate::from_ymd_opt(1912, 7, 30).unwrap()
886        );
887        assert!(parse_with_settings("令和0年11月26日", &s).is_none());
888
889        // Italian & Spanish prepositions/connectors
890        let it_dt = get_date_data("il 15 gennaio 2026 alle 14:30", &s);
891        assert_eq!(it_dt.locale.as_deref(), Some("it"));
892        assert_eq!(
893            it_dt.date_obj.unwrap().naive_local(),
894            NaiveDate::from_ymd_opt(2026, 1, 15)
895                .unwrap()
896                .and_hms_opt(14, 30, 0)
897                .unwrap()
898        );
899        assert_eq!(
900            parse_with_settings("el 15 de enero de 2026 a las 14:30", &s)
901                .unwrap()
902                .naive_local(),
903            NaiveDate::from_ymd_opt(2026, 1, 15)
904                .unwrap()
905                .and_hms_opt(14, 30, 0)
906                .unwrap()
907        );
908    }
909
910    #[test]
911    fn test_v050_negative_timestamp_micros_and_localized_date_formats() {
912        let s = fixed_settings();
913        // Disabled by default
914        assert!(parse_with_settings("-86400", &s).is_none());
915
916        // Enabled explicitly via PARSERS=[NegativeTimestamp]
917        let mut s_neg = fixed_settings();
918        s_neg.parsers = Some(vec![ParserKind::NegativeTimestamp]);
919        assert_eq!(
920            parse_with_settings("-86400", &s_neg).unwrap().naive_local(),
921            NaiveDate::from_ymd_opt(1969, 12, 31)
922                .unwrap()
923                .and_hms_opt(0, 0, 0)
924                .unwrap()
925        );
926        assert_eq!(
927            parse_with_settings("-86400.5", &s_neg).unwrap().naive_local(),
928            NaiveDateTime::parse_from_str("1969-12-30 23:59:59.500", "%Y-%m-%d %H:%M:%S%.3f")
929                .unwrap()
930        );
931        assert!(parse_with_settings("-2026", &s_neg).is_none());
932
933        // 16-digit positive microsecond timestamp
934        assert_eq!(
935            parse_with_settings("1700000000123456", &s)
936                .unwrap()
937                .naive_local(),
938            DateTime::from_timestamp_micros(1700000000123456)
939                .unwrap()
940                .naive_utc()
941        );
942
943        // Localized strict custom date_formats (%B in Turkish & French)
944        let mut s_fmt = fixed_settings();
945        s_fmt.parsers = Some(vec![ParserKind::CustomFormats]);
946        s_fmt.date_formats = Some(vec!["%d %B %Y".to_string()]);
947        let tr_m = get_date_data("15 Ocak 2026", &s_fmt);
948        assert_eq!(tr_m.locale.as_deref(), Some("tr"));
949        assert_eq!(
950            tr_m.date_obj.unwrap().naive_local().date(),
951            NaiveDate::from_ymd_opt(2026, 1, 15).unwrap()
952        );
953        let fr_m = get_date_data("15 janvier 2026", &s_fmt);
954        assert_eq!(fr_m.locale.as_deref(), Some("fr"));
955        assert_eq!(
956            fr_m.date_obj.unwrap().naive_local().date(),
957            NaiveDate::from_ymd_opt(2026, 1, 15).unwrap()
958        );
959        assert!(parse_with_settings("15-01-2026", &s_fmt).is_none());
960    }
961
962    #[test]
963    fn test_v050_js_ctime_tz_world_abbrevs_and_parenthetical_guard() {
964        let s = fixed_settings();
965
966        // JavaScript Date.toString() formats with parenthesized TZ comments
967        let js1 = parse_with_settings("Thu Nov 26 2026 14:30:00 GMT+0300 (GMT+03:00)", &s).unwrap();
968        assert!(js1.is_aware());
969        assert_eq!(
970            js1.naive_local(),
971            NaiveDateTime::parse_from_str("2026-11-26 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
972        );
973        let js2 = parse_with_settings("Thu Nov 26 2026 14:30:00 GMT+0300 (Turkey Time)", &s).unwrap();
974        assert!(js2.is_aware());
975        assert_eq!(
976            js2.naive_local(),
977            NaiveDateTime::parse_from_str("2026-11-26 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
978        );
979        // Guard against arbitrary parenthesized text
980        assert!(parse_with_settings("Meeting (urgent)", &s).is_none());
981
982        // Unix ctime mid-string timezone before trailing 4-digit year
983        let ct1 = parse_with_settings("Thu Nov 26 14:30:00 UTC 2026", &s).unwrap();
984        assert!(ct1.is_aware());
985        assert_eq!(
986            ct1.naive_local(),
987            NaiveDateTime::parse_from_str("2026-11-26 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
988        );
989        let ct2 = parse_with_settings("Mon Jan 15 09:00:00 CEST 2026", &s).unwrap();
990        assert!(ct2.is_aware());
991        assert_eq!(
992            ct2.naive_local(),
993            NaiveDateTime::parse_from_str("2026-01-15 09:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
994        );
995
996        // Extended world timezone abbreviations + IST/BST backward-compat preserved
997        for tz_str in [
998            "15 Jan 2026 14:30 PKT",
999            "15 Jan 2026 14:30 WIB",
1000            "15 Jan 2026 14:30 WITA",
1001            "15 Jan 2026 14:30 WIT",
1002            "15 Jan 2026 14:30 PHT",
1003            "15 Jan 2026 14:30 NPT",
1004            "15 Jan 2026 14:30 ACST",
1005            "15 Jan 2026 14:30 ACDT",
1006            "15 Jan 2026 14:30 CLT",
1007            "15 Jan 2026 14:30 COT",
1008            "15 Jan 2026 14:30 IRST",
1009            "15 Jan 2026 14:30 AFT",
1010            "15 Jan 2026 14:30 UZT",
1011            "15 Jan 2026 14:30 ALMT",
1012        ] {
1013            let parsed = parse_with_settings(tz_str, &s).unwrap();
1014            assert!(parsed.is_aware(), "expected aware for {}", tz_str);
1015            assert_eq!(parsed.naive_local().hour(), 14);
1016        }
1017    }
1018
1019    #[test]
1020    fn test_v050_no_spaces_12_14_prefixed_time_and_cjk_korean_relatives() {
1021        let s = fixed_settings();
1022
1023        // 12/14-digit no-spaces-time gated behind PARSERS=[NoSpacesTime]
1024        assert!(parse_with_settings("202601151430", &s).is_none());
1025        let mut s_ns = fixed_settings();
1026        s_ns.parsers = Some(vec![ParserKind::NoSpacesTime]);
1027        assert_eq!(
1028            parse_with_settings("202601151430", &s_ns).unwrap().naive_local(),
1029            NaiveDateTime::parse_from_str("2026-01-15 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
1030        );
1031        assert_eq!(
1032            parse_with_settings("20260115143045", &s_ns).unwrap().naive_local(),
1033            NaiveDateTime::parse_from_str("2026-01-15 14:30:45", "%Y-%m-%d %H:%M:%S").unwrap()
1034        );
1035        s_ns.date_order = Some(DateOrder::DMY);
1036        assert_eq!(
1037            parse_with_settings("150120261430", &s_ns).unwrap().naive_local(),
1038            NaiveDateTime::parse_from_str("2026-01-15 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
1039        );
1040
1041        // "just now", "at 5:30 PM", "2026-11-26 t 14:30", "tomorrow at 5"
1042        assert_eq!(
1043            parse_with_settings("just now", &s).unwrap().naive_local(),
1044            s.relative_base.unwrap()
1045        );
1046        assert_eq!(
1047            parse_with_settings("at 5:30 PM", &s).unwrap().naive_local(),
1048            NaiveDateTime::parse_from_str("2026-11-26 17:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
1049        );
1050        assert_eq!(
1051            parse_with_settings("2026-11-26 t 14:30", &s).unwrap().naive_local(),
1052            NaiveDateTime::parse_from_str("2026-11-26 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
1053        );
1054        assert_eq!(
1055            parse_with_settings("tomorrow at 5", &s).unwrap().naive_local(),
1056            NaiveDateTime::parse_from_str("2026-11-27 05:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
1057        );
1058
1059        // Multi-unit attached & CJK/Korean relative+time
1060        assert_eq!(
1061            parse_with_settings("3日2時間前", &s).unwrap().naive_local(),
1062            NaiveDateTime::parse_from_str("2026-11-23 13:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
1063        );
1064        assert_eq!(
1065            parse_with_settings("昨日の14:30", &s).unwrap().naive_local(),
1066            NaiveDateTime::parse_from_str("2026-11-25 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
1067        );
1068        assert_eq!(
1069            parse_with_settings("昨日の午後2時30分", &s).unwrap().naive_local(),
1070            NaiveDateTime::parse_from_str("2026-11-25 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
1071        );
1072        assert_eq!(
1073            parse_with_settings("어제 오후 2시 30분", &s).unwrap().naive_local(),
1074            NaiveDateTime::parse_from_str("2026-11-25 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
1075        );
1076        assert_eq!(
1077            parse_with_settings("2일 3시간 전", &s).unwrap().naive_local(),
1078            NaiveDateTime::parse_from_str("2026-11-24 12:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
1079        );
1080        assert_eq!(
1081            parse_with_settings("1h30m ago", &s).unwrap().naive_local(),
1082            NaiveDateTime::parse_from_str("2026-11-26 13:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
1083        );
1084    }
1085
1086    #[test]
1087    fn test_v050_partial_formats_search_cjk_and_remaining_idioms() {
1088        let s = fixed_settings();
1089
1090        // Partial date_formats
1091        let mut s_fmt = fixed_settings();
1092        s_fmt.parsers = Some(vec![ParserKind::CustomFormats]);
1093        for (inp, fmt, exp) in [
1094            ("November 2026", "%B %Y", "2026-11-26 00:00:00"),
1095            ("2026-11", "%Y-%m", "2026-11-26 00:00:00"),
1096            ("15 Ocak", "%d %B", "2026-01-15 00:00:00"),
1097            ("14:30", "%H:%M", "2026-11-26 14:30:00"),
1098            ("2026-330", "%Y-%j", "2026-11-26 00:00:00"),
1099        ] {
1100            s_fmt.date_formats = Some(vec![fmt.to_string()]);
1101            assert_eq!(
1102                parse_with_settings(inp, &s_fmt).unwrap().naive_local(),
1103                NaiveDateTime::parse_from_str(exp, "%Y-%m-%d %H:%M:%S").unwrap(),
1104                "failed partial custom format {} with {}",
1105                inp,
1106                fmt
1107            );
1108        }
1109
1110        // search_dates custom date_formats + precise CJK spans
1111        let mut s_search_fmt = fixed_settings();
1112        s_search_fmt.date_formats = Some(vec!["%Y_%m_%d".to_string()]);
1113        let custom_found = search_dates_full("Release 2026_11_26 is live now.", &s_search_fmt);
1114        assert_eq!(custom_found.len(), 2);
1115        assert_eq!(custom_found[0].text, "2026_11_26");
1116        assert_eq!(custom_found[1].text, "now");
1117
1118        let ja_found = search_dates_full("締め切りは2026年11月26日です。", &s);
1119        assert_eq!(ja_found.len(), 1);
1120        assert_eq!(ja_found[0].text, "2026年11月26日");
1121
1122        let zh_found = search_dates_full("会议定于2026年11月26日举行。", &s);
1123        assert_eq!(zh_found.len(), 1);
1124        assert_eq!(zh_found[0].text, "2026年11月26日");
1125
1126        let multi_cjk = search_dates_full("2026年11月20日から2026年11月26日まで", &s);
1127        assert_eq!(multi_cjk.len(), 2);
1128        assert_eq!(multi_cjk[0].text, "2026年11月20日");
1129        assert_eq!(multi_cjk[1].text, "2026年11月26日");
1130
1131        // Remaining 9 multilingual idioms + approx markers
1132        for (inp, exp) in [
1133            ("~3 days ago", "2026-11-23 15:00:00"),
1134            ("about 2 hours ago", "2026-11-26 13:00:00"),
1135            ("yaklaşık 2 saat önce", "2026-11-26 13:00:00"),
1136            ("約2時間前", "2026-11-26 13:00:00"),
1137            ("12 noon", "2026-11-26 12:00:00"),
1138            ("12 midnight", "2026-11-26 00:00:00"),
1139            ("next Monday morning", "2026-11-30 09:00:00"),
1140            ("через полчаса", "2026-11-26 15:30:00"),
1141            ("半小时前", "2026-11-26 14:30:00"),
1142            ("منذ يومين", "2026-11-24 15:00:00"),
1143            ("לפני שעתיים", "2026-11-26 13:00:00"),
1144        ] {
1145            assert_eq!(
1146                parse_with_settings(inp, &s).unwrap().naive_local(),
1147                NaiveDateTime::parse_from_str(exp, "%Y-%m-%d %H:%M:%S").unwrap(),
1148                "failed idiom {}",
1149                inp
1150            );
1151        }
1152    }
1153
1154    #[test]
1155    fn test_v060_time_period_iso_month_guard_and_205_scripts() {
1156        let mut s_tp = fixed_settings();
1157        s_tp.return_time_as_period = true;
1158        for expr in ["2 hours ago", "30 minutes ago", "half an hour ago", "через полчаса"] {
1159            let dd = get_date_data(expr, &s_tp);
1160            assert!(dd.date_obj.is_some(), "failed {}", expr);
1161            assert_eq!(dd.period, Period::Time, "expected Period::Time for {}", expr);
1162        }
1163
1164        // Invalid month "2026-13-01" falls back to YDM under default None, returns None under StrictDateOrder::All
1165        let mut s_strict = fixed_settings();
1166        s_strict.strict_date_order = StrictDateOrder::All;
1167        assert!(parse_with_settings("2026-13-01", &s_strict).is_none());
1168        let s = fixed_settings();
1169        assert_eq!(
1170            parse_with_settings("2026-13-01", &s).unwrap().naive_local().date(),
1171            NaiveDate::from_ymd_opt(2026, 1, 13).unwrap()
1172        );
1173        let mut s_ydm = fixed_settings();
1174        s_ydm.date_order = Some(DateOrder::YDM);
1175        assert_eq!(
1176            parse_with_settings("2026-13-01", &s_ydm).unwrap().naive_local().date(),
1177            NaiveDate::from_ymd_opt(2026, 1, 13).unwrap()
1178        );
1179
1180        // Newly enriched scripts & languages (bo, or, chr, zgh, ii, tl, eo, yo, haw, qu)
1181        for (lang, expr) in [
1182            ("bo", "གཉིས ཉིན སྔོན་ལ"),
1183            ("or", "ସକାଳ"),
1184            ("chr", "ᏌᎾᎴ"),
1185            ("zgh", "ⵜⵉⴼⴰⵡⵜ"),
1186            ("ii", "ꎮꂷ"),
1187            ("tl", "kahapon"),
1188            ("eo", "antaŭ 3 jaroj"),
1189            ("yo", "àárọ̀"),
1190            ("haw", "3 lā i hala"),
1191            ("qu", "ñawpaq 3 wata"),
1192        ] {
1193            let mut s_l = fixed_settings();
1194            s_l.languages = Some(vec![lang.to_string()]);
1195            assert!(
1196                parse_with_settings(expr, &s_l).is_some(),
1197                "failed {} for {}",
1198                expr,
1199                lang
1200            );
1201        }
1202    }
1203
1204    #[test]
1205    fn test_v061_parity_fixes() {
1206        // 1. %f microseconds in date_formats
1207        let mut s_fmt = fixed_settings();
1208        s_fmt.date_formats = Some(vec!["%Y-%m-%d %H:%M:%S.%f".to_string()]);
1209        let dt_us = parse_with_settings("2024-05-15 14:30:00.123456", &s_fmt)
1210            .unwrap()
1211            .naive_local();
1212        assert_eq!(dt_us.and_utc().timestamp_subsec_micros(), 123456);
1213        let mut s_custom_only = s_fmt.clone();
1214        s_custom_only.parsers = Some(vec![ParserKind::CustomFormats]);
1215        assert!(parse_with_settings("2024-05-15 14:30:00", &s_custom_only).is_none());
1216
1217        // 2. STRICT_PARSING=True allows relative dates while rejecting incomplete absolutes
1218        let mut s_strict = fixed_settings();
1219        s_strict.strict_parsing = true;
1220        assert_eq!(
1221            parse_with_settings("yesterday", &s_strict).unwrap().naive_local(),
1222            NaiveDateTime::parse_from_str("2026-11-25 15:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
1223        );
1224        assert!(parse_with_settings("May 2024", &s_strict).is_none());
1225
1226        // 3. Attached short hour relatives (in 3h, il y a 3h, dans 3h)
1227        let s = fixed_settings();
1228        for (inp, exp) in [
1229            ("in 3h", "2026-11-26 18:00:00"),
1230            ("il y a 3h", "2026-11-26 12:00:00"),
1231            ("dans 3h", "2026-11-26 18:00:00"),
1232        ] {
1233            assert_eq!(
1234                parse_with_settings(inp, &s).unwrap().naive_local(),
1235                NaiveDateTime::parse_from_str(exp, "%Y-%m-%d %H:%M:%S").unwrap(),
1236                "failed {}",
1237                inp
1238            );
1239        }
1240
1241        // 4. ro / sk connectors & Minguo direct era
1242        assert_eq!(
1243            parse_with_settings("15 mai 2024 la ora 15:30", &s).unwrap().naive_local(),
1244            NaiveDateTime::parse_from_str("2024-05-15 15:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
1245        );
1246        assert_eq!(
1247            parse_with_settings("15. mája 2024 o 15:30", &s).unwrap().naive_local(),
1248            NaiveDateTime::parse_from_str("2024-05-15 15:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
1249        );
1250        assert_eq!(
1251            parse_with_settings("民國113年5月15日", &s).unwrap().naive_local().date(),
1252            NaiveDate::from_ymd_opt(2024, 5, 15).unwrap()
1253        );
1254
1255        // 5. search_dates CJK multi-date & Arabic/Spanish connectors
1256        let ja_hits = crate::search::search_dates("会議は2024年5月15日14:30からです。3日前に通知済み。", &s);
1257        assert_eq!(ja_hits.len(), 2);
1258        assert_eq!(ja_hits[0].0, "2024年5月15日14:30");
1259        assert_eq!(ja_hits[1].0, "3日前");
1260
1261        let zh_hits = crate::search::search_dates("会议定于2024年5月15日下午3点,2天前已发送邀请。", &s);
1262        assert_eq!(zh_hits.len(), 2);
1263        assert_eq!(zh_hits[0].0, "2024年5月15日下午3点");
1264        assert_eq!(zh_hits[1].0, "2天前");
1265    }
1266
1267    #[test]
1268    fn test_p0_safety_and_correctness() {
1269        let s = fixed_settings();
1270
1271        // Non-ASCII whitespace must never panic
1272        assert!(parse_with_settings("2024-03-15\u{00A0}14:30", &s).is_some());
1273        assert!(parse_with_settings("15\u{202F}March\u{202F}2024", &s).is_some());
1274        assert!(parse_with_settings("2024年3月15日\u{3000}14時30分", &s).is_some());
1275        assert!(parse_with_settings("hello\u{00A0}world", &s).is_none());
1276
1277        // Range UTF-8 & Turkish 'İ' safety
1278        assert_eq!(
1279            parse_date_range("12 NİSAN - 15 MAYIS 2026", &s)
1280                .unwrap()
1281                .1
1282                .naive_local()
1283                .date(),
1284            NaiveDate::from_ymd_opt(2026, 5, 15).unwrap()
1285        );
1286        assert!(parse_date_range("2月-5日", &s).is_none());
1287
1288        // CJK standalone tokens in search_dates + Japanese PM/AM
1289        let cjk = crate::search::search_dates("Meeting: 2026年5月10日", &s);
1290        assert_eq!(cjk.len(), 1);
1291        assert_eq!(cjk[0].0, "2026年5月10日");
1292        assert_eq!(
1293            parse_with_settings("2026年3月15日 午後2時30分", &s)
1294                .unwrap()
1295                .naive_local(),
1296            NaiveDateTime::parse_from_str("2026-03-15 14:30:00", "%Y-%m-%d %H:%M:%S").unwrap()
1297        );
1298
1299        // Locale scoring dominance ("Jun" -> en month June, not fy evening)
1300        let jun_dd = get_date_data("Jun", &s);
1301        assert_eq!(jun_dd.locale.as_deref(), Some("en"));
1302        assert_eq!(jun_dd.date_obj.unwrap().naive_local().month(), 6);
1303        assert!(get_date_data("15 mar 2026 alle 14:30", &s).date_obj.is_some());
1304        assert!(get_date_data("15 mai 2026 kell 14:30", &s).date_obj.is_some());
1305        assert!(get_date_data("15 jun 2026 pukul 14:30", &s).date_obj.is_some());
1306
1307        // Calendar bounds & rollovers
1308        #[cfg(feature = "calendars")]
1309        {
1310            assert!(calendars::jalali_to_gregorian(11767034, 1, 1).is_none());
1311            assert!(calendars::hijri_to_gregorian(6066335, 1, 1).is_none());
1312            assert!(calendars::french_republican_to_gregorian(50_000_000, 7, 14).is_none());
1313        }
1314        assert!(parse_with_settings("0000-W01-1", &s).is_none());
1315        let mut s_tz = s.clone();
1316        s_tz.to_timezone = Some("Asia/Tokyo".to_string());
1317        assert!(parse_with_settings("9999-12-31 23:00:00 UTC", &s_tz).is_none());
1318    }
1319}