Skip to main content

dateoxide_core/
absolute.rs

1use crate::fast_path::{days_in_month, expand_two_digit_year, parse_time_str, resolve_missing_day};
2use crate::locale::{fold_diacritics, CompiledLocale, LocaleRegistry};
3use crate::settings::{
4    DateOrder, DatePart, PartOfDay, Period, PreferDatesFrom, PreferMonthOfYear, Settings,
5    StrictDateOrder,
6};
7use chrono::{Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike};
8
9#[derive(Debug, Clone)]
10pub struct AbsoluteMatch {
11    pub naive: NaiveDateTime,
12    pub period: Period,
13    pub locale: String,
14    pub has_time: bool,
15    pub parts: Vec<&'static str>,
16    pub part_of_day: Option<PartOfDay>,
17}
18
19/// Try parsing a natural-language absolute or partial date across candidate locales.
20pub fn try_parse_absolute(
21    normalized: &str,
22    candidate_ids: &[usize],
23    registry: &LocaleRegistry,
24    settings: &Settings,
25) -> Option<AbsoluteMatch> {
26    if normalized.contains('年')
27        || normalized.contains('月')
28        || normalized.contains('日')
29        || normalized.contains('년')
30        || normalized.contains('월')
31        || normalized.contains('일')
32    {
33        if let Some(m) = try_cjk_or_korean_date(normalized, settings) {
34            return Some(m);
35        }
36    }
37
38    if normalized.len() == 4 && normalized.bytes().all(|b| b.is_ascii_digit()) {
39        if !settings.strict_parsing
40            && !settings.require_parts.contains(&DatePart::Month)
41            && !settings.require_parts.contains(&DatePart::Day)
42        {
43            if let Ok(year) = normalized.parse::<i32>() {
44                if (1000..=2999).contains(&year) {
45                    let base = settings.effective_base();
46                    let month = match settings.prefer_month_of_year {
47                        PreferMonthOfYear::First => 1,
48                        PreferMonthOfYear::Last => 12,
49                        PreferMonthOfYear::Current => base.month(),
50                    };
51                    let day = resolve_missing_day(year, month, base.day(), settings.prefer_day_of_month);
52                    if let Some(nd) = NaiveDate::from_ymd_opt(year, month, day) {
53                        return Some(AbsoluteMatch {
54                            naive: nd.and_hms_opt(0, 0, 0)?,
55                            period: Period::Year,
56                            locale: "en".to_string(),
57                            has_time: false,
58                            parts: vec!["year"],
59                            part_of_day: None,
60                        });
61                    }
62                }
63            }
64        }
65        return None;
66    }
67
68    for &lid in candidate_ids {
69        let loc = &registry.locales[lid];
70        if let Some(m) = try_parse_in_locale(normalized, loc, settings) {
71            return Some(m);
72        }
73    }
74
75    None
76}
77
78fn extract_japanese_era_year(s: &str) -> Option<Result<(i32, String), ()>> {
79    const ERAS: [(&str, i32); 5] = [
80        ("令和", 2018),
81        ("平成", 1988),
82        ("昭和", 1925),
83        ("大正", 1911),
84        ("明治", 1867),
85    ];
86    for &(era, base) in &ERAS {
87        if let Some(pos) = s.find(era) {
88            let after_era = &s[pos + era.len()..];
89            let trimmed = after_era.trim_start();
90            let ws_skipped = after_era.len() - trimmed.len();
91            let mut cursor = pos + era.len() + ws_skipped;
92
93            let era_num: i32 = if let Some(rest) = trimmed.strip_prefix('元') {
94                let rest_trim = rest.trim_start();
95                let nen_ws = rest.len() - rest_trim.len();
96                if !rest_trim.starts_with('年') {
97                    return Some(Err(()));
98                }
99                cursor += '元'.len_utf8() + nen_ws + '年'.len_utf8();
100                1
101            } else {
102                let mut d_end = 0usize;
103                for (i, ch) in trimmed.char_indices() {
104                    if ch.is_ascii_digit() {
105                        d_end = i + 1;
106                    } else {
107                        break;
108                    }
109                }
110                if d_end == 0 || d_end > 2 {
111                    return Some(Err(()));
112                }
113                let val: i32 = match trimmed[..d_end].parse() {
114                    Ok(v) if (1..=99).contains(&v) => v,
115                    _ => return Some(Err(())),
116                };
117                let after_digits = &trimmed[d_end..];
118                let rest_trim = after_digits.trim_start();
119                let nen_ws = after_digits.len() - rest_trim.len();
120                if !rest_trim.starts_with('年') {
121                    return Some(Err(()));
122                }
123                cursor += d_end + nen_ws + '年'.len_utf8();
124                val
125            };
126
127            let mut rem = String::with_capacity(s.len());
128            rem.push_str(&s[..pos]);
129            rem.push_str(&s[cursor..]);
130            return Some(Ok((base + era_num, rem)));
131        }
132    }
133    None
134}
135
136fn try_cjk_or_korean_date(s: &str, settings: &Settings) -> Option<AbsoluteMatch> {
137    let mut year: Option<i32> = None;
138    let mut month: Option<u32> = None;
139    let mut day: Option<u32> = None;
140    let mut hour: u32 = 0;
141    let mut minute: u32 = 0;
142    let mut second: u32 = 0;
143    let mut has_time = false;
144    let mut is_japanese = false;
145    let owned_rem;
146    let scan_s: &str = match extract_japanese_era_year(s) {
147        Some(Ok((gy, rem))) => {
148            year = Some(gy);
149            is_japanese = true;
150            owned_rem = rem;
151            &owned_rem
152        }
153        Some(Err(())) => return None,
154        None => s,
155    };
156
157    let is_korean =
158        scan_s.contains('년') || scan_s.contains('월') || scan_s.contains('일') || scan_s.contains('시');
159    let is_pm = scan_s.contains("오후") || scan_s.contains("pm") || scan_s.contains("下午");
160    let is_am = scan_s.contains("오전") || scan_s.contains("am") || scan_s.contains("上午");
161
162    let mut loose_nums: Vec<(u32, usize)> = Vec::new();
163    let mut cur_num = String::new();
164    let chars: Vec<char> = scan_s.chars().collect();
165    let mut idx = 0usize;
166
167    while idx < chars.len() {
168        let ch = chars[idx];
169        if ch.is_ascii_digit() {
170            cur_num.push(ch);
171            idx += 1;
172            continue;
173        }
174        if ch.is_whitespace() {
175            // Look ahead past whitespace: if followed by CJK/Korean suffix, keep cur_num attached!
176            let mut la = idx + 1;
177            while la < chars.len() && chars[la].is_whitespace() {
178                la += 1;
179            }
180            if la < chars.len()
181                && matches!(
182                    chars[la],
183                    '年' | '년' | '月' | '월' | '日' | '号' | '일' | '時' | '时' | '시' | '分' | '분' | '秒' | '초'
184                )
185            {
186                idx += 1;
187                continue;
188            }
189        }
190        if !cur_num.is_empty() {
191            let val: u32 = cur_num.parse().ok()?;
192            let len = cur_num.len();
193            cur_num.clear();
194            match ch {
195                '年' | '년' => {
196                    year = Some(if len <= 2 {
197                        expand_two_digit_year(val)
198                    } else {
199                        val as i32
200                    });
201                }
202                '月' | '월' => month = Some(val),
203                '日' | '号' | '일' => day = Some(val),
204                '時' | '时' | '시' => {
205                    hour = val;
206                    has_time = true;
207                }
208                '分' | '분' => {
209                    minute = val;
210                    has_time = true;
211                }
212                '秒' | '초' => {
213                    second = val;
214                    has_time = true;
215                }
216                ':' => {
217                    // Handle attached day+hour like "2016年6月2911:30" -> day=29, hour=11
218                    if len == 4 && day.is_none() {
219                        let d_cand = val / 100;
220                        let h_cand = val % 100;
221                        if (1..=31).contains(&d_cand) && h_cand <= 23 {
222                            day = Some(d_cand);
223                            let byte_idx = scan_s
224                                .char_indices()
225                                .nth(idx)
226                                .map(|(b, _)| b)
227                                .unwrap_or(0);
228                            if let Some(t) = parse_time_str(&format!("{}{}", h_cand, &scan_s[byte_idx..])) {
229                                hour = t.hour();
230                                minute = t.minute();
231                                second = t.second();
232                                has_time = true;
233                                break;
234                            }
235                        }
236                    }
237                    let byte_idx = scan_s
238                        .char_indices()
239                        .nth(idx)
240                        .map(|(b, _)| b)
241                        .unwrap_or(0);
242                    let start = scan_s[..byte_idx]
243                        .char_indices()
244                        .rev()
245                        .find(|&(_, c)| !c.is_ascii_digit())
246                        .map(|(p, c)| p + c.len_utf8())
247                        .unwrap_or(0);
248                    if let Some(t) = parse_time_str(scan_s[start..].trim()) {
249                        hour = t.hour();
250                        minute = t.minute();
251                        second = t.second();
252                        has_time = true;
253                        break;
254                    }
255                }
256                _ => loose_nums.push((val, len)),
257            }
258        }
259        idx += 1;
260    }
261
262    if !cur_num.is_empty() {
263        let len = cur_num.len();
264        if let Ok(val) = cur_num.parse::<u32>() {
265            loose_nums.push((val, len));
266        }
267    }
268
269    for (val, len) in loose_nums {
270        if year.is_none() && len == 4 && (1000..=2999).contains(&val) {
271            year = Some(val as i32);
272        } else if day.is_none() && (1..=31).contains(&val) && len <= 2 {
273            day = Some(val);
274        }
275    }
276
277    if year.is_none() && month.is_none() {
278        return None;
279    }
280
281    let mut part_of_day: Option<PartOfDay> = None;
282    let mut tod_time: Option<NaiveTime> = None;
283    if has_time {
284        if is_pm && hour >= 1 && hour < 12 {
285            hour += 12;
286        } else if is_am && hour == 12 {
287            hour = 0;
288        }
289    } else {
290        let tod_hour: Option<u8> = [
291            ("真夜中", 0u8),
292            ("午夜", 0),
293            ("자정", 0),
294            ("早上", 9),
295            ("上午", 9),
296            ("아침", 9),
297            ("오전", 9),
298            ("朝", 9),
299            ("正午", 12),
300            ("中午", 12),
301            ("정오", 12),
302            ("午後", 15),
303            ("下午", 15),
304            ("오후", 15),
305            ("夕方", 18),
306            ("傍晚", 18),
307            ("저녁", 18),
308            ("晚上", 20),
309            ("夜", 20),
310            ("밤", 20),
311        ]
312        .into_iter()
313        .find(|(tok, _)| scan_s.contains(tok))
314        .map(|(_, h)| h);
315
316        if let Some(h) = tod_hour {
317            has_time = true;
318            part_of_day = PartOfDay::from_hour(h);
319            if h == 0 || h == 12 {
320                tod_time = NaiveTime::from_hms_opt(h as u32, 0, 0);
321            } else if let Some(p) = part_of_day {
322                tod_time = Some(settings.parts_of_day.time_for(p));
323            }
324        }
325    }
326
327    let base = settings.effective_base();
328    let (y, m, d, period, parts) = complete_partial_date(year, month, day, has_time, base, settings)?;
329    let nd = NaiveDate::from_ymd_opt(y, m, d)?;
330    let nt = tod_time.or_else(|| NaiveTime::from_hms_opt(hour, minute, second))?;
331    let lang = if is_korean {
332        "ko"
333    } else if is_japanese
334        || scan_s.contains('時')
335        || scan_s.contains('朝')
336        || scan_s.contains('夜')
337        || scan_s.contains("夕方")
338        || scan_s.contains("正午")
339        || scan_s.contains("真夜中")
340    {
341        "ja"
342    } else {
343        "zh"
344    };
345
346    Some(AbsoluteMatch {
347        naive: nd.and_time(nt),
348        period,
349        locale: lang.to_string(),
350        has_time,
351        parts,
352        part_of_day,
353    })
354}
355
356fn lookup_month(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<u8> {
357    if let Some(&m) = loc.months.get(s) {
358        return Some(m);
359    }
360    if normalize {
361        let f = fold_diacritics(s);
362        if let Some(&m) = loc.folded_months.get(&f) {
363            return Some(m);
364        }
365    }
366    None
367}
368
369fn lookup_weekday(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<u8> {
370    if let Some(&w) = loc.weekdays.get(s) {
371        return Some(w);
372    }
373    if normalize {
374        let f = fold_diacritics(s);
375        if let Some(&w) = loc.folded_weekdays.get(&f) {
376            return Some(w);
377        }
378    }
379    None
380}
381
382fn lookup_tod_hour(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<u8> {
383    if let Some(&h) = loc.time_of_day.get(s) {
384        return Some(h);
385    }
386    if normalize {
387        let f = fold_diacritics(s);
388        if let Some(&h) = loc.folded_time_of_day.get(&f).or_else(|| loc.time_of_day.get(&f)) {
389            return Some(h);
390        }
391    }
392    None
393}
394
395fn tod_hour_to_time_and_pod(hour: u8, settings: &Settings) -> (NaiveTime, Option<PartOfDay>) {
396    match hour {
397        3 | 6 => (settings.parts_of_day.time_for(PartOfDay::EarlyMorning), Some(PartOfDay::EarlyMorning)),
398        9 => (settings.parts_of_day.time_for(PartOfDay::Morning), Some(PartOfDay::Morning)),
399        15 => (settings.parts_of_day.time_for(PartOfDay::Afternoon), Some(PartOfDay::Afternoon)),
400        18 => (settings.parts_of_day.time_for(PartOfDay::Evening), Some(PartOfDay::Evening)),
401        20 => (settings.parts_of_day.time_for(PartOfDay::Night), Some(PartOfDay::Night)),
402        12 => (NaiveTime::from_hms_opt(12, 0, 0).unwrap(), None),
403        0 => (NaiveTime::from_hms_opt(0, 0, 0).unwrap(), None),
404        h => (NaiveTime::from_hms_opt(h as u32, 0, 0).unwrap(), None),
405    }
406}
407
408fn try_parse_in_locale(
409    normalized: &str,
410    loc: &CompiledLocale,
411    settings: &Settings,
412) -> Option<AbsoluteMatch> {
413    let raw_tokens = split_date_tokens(normalized, loc, settings.normalize);
414    if raw_tokens.is_empty() || raw_tokens.len() > 18 {
415        return None;
416    }
417
418    let mut year: Option<i32> = None;
419    let mut month: Option<u32> = None;
420    let mut day: Option<u32> = None;
421    let mut weekday_seen: Option<u8> = None;
422    let mut time: Option<NaiveTime> = None;
423    let mut part_of_day: Option<PartOfDay> = None;
424    let mut ampm: Option<bool> = None;
425    let mut free_nums: Vec<(u32, usize)> = Vec::new();
426    let mut matched_locale_signal = false;
427
428    let mut i = 0;
429    while i < raw_tokens.len() {
430        let tok = raw_tokens[i];
431        let clean = tok.trim_matches(|c: char| matches!(c, ',' | '.' | '(' | ')' | '[' | ']'));
432        if clean.is_empty() {
433            i += 1;
434            continue;
435        }
436
437        if settings
438            .skip_tokens
439            .iter()
440            .any(|st| st.eq_ignore_ascii_case(clean))
441        {
442            i += 1;
443            continue;
444        }
445
446        // 1. Apache / Nginx combined year:HH:MM:SS token (e.g. "2026:15:30:00")
447        if year.is_none() && time.is_none() && clean.len() >= 12 {
448            if let Some((y_part, t_part)) = clean.split_once(':') {
449                if y_part.len() == 4 && y_part.bytes().all(|b| b.is_ascii_digit()) {
450                    if let (Ok(y_val), Some(t_val)) = (y_part.parse::<i32>(), parse_time_str(t_part)) {
451                        if (1000..=2999).contains(&y_val) {
452                            year = Some(y_val);
453                            time = Some(t_val);
454                            i += 1;
455                            continue;
456                        }
457                    }
458                }
459            }
460        }
461
462        // 2. Time token (including dot-separated HH.MM with optional German Uhr / Finnish ip.)
463        if time.is_none()
464            && (clean.contains(':')
465                || (clean.len() >= 4
466                    && clean.contains('.')
467                    && clean.as_bytes()[0].is_ascii_digit()
468                    && clean.matches('.').count() == 1)
469                || (clean.len() >= 3
470                    && clean.as_bytes()[0].is_ascii_digit()
471                    && (clean.contains('h')
472                        || clean.ends_with("am")
473                        || clean.ends_with("pm")
474                        || clean.ends_with("a.m")
475                        || clean.ends_with("p.m")
476                        || tok.ends_with("a.m.")
477                        || tok.ends_with("p.m."))))
478        {
479            let time_cand = if tok.ends_with("a.m.") || tok.ends_with("p.m.") {
480                tok.trim_matches(',')
481            } else {
482                clean
483            };
484            if i + 1 < raw_tokens.len() {
485                let next_clean = raw_tokens[i + 1].trim_matches(|c: char| c == '.' || c == ',');
486                if next_clean == "am"
487                    || next_clean == "pm"
488                    || next_clean == "a.m"
489                    || next_clean == "p.m"
490                    || next_clean == "ip"
491                    || next_clean == "ap"
492                    || next_clean == "uhr"
493                    || loc.am.contains(next_clean)
494                    || loc.pm.contains(next_clean)
495                {
496                    let combined = format!("{} {}", time_cand, raw_tokens[i + 1].trim_matches(','));
497                    if let Some(t) = parse_time_str(&combined) {
498                        time = Some(t);
499                        i += 2;
500                        continue;
501                    }
502                }
503            }
504            if let Some(t) = parse_time_str(time_cand) {
505                time = Some(t);
506                i += 1;
507                continue;
508            }
509        }
510
511        // 3. Month name: trigram -> bigram -> unigram
512        if month.is_none() {
513            let mut matched_span = 0usize;
514            for span in (1..=5).rev() {
515                if i + span <= raw_tokens.len() {
516                    let cand = if span == 1 {
517                        clean.to_string()
518                    } else {
519                        let mut s = String::from(clean);
520                        for k in 1..span {
521                            s.push(' ');
522                            s.push_str(raw_tokens[i + k].trim_matches(','));
523                        }
524                        s
525                    };
526                    if let Some(m) = lookup_month(&cand, loc, settings.normalize) {
527                        month = Some(m as u32);
528                        matched_locale_signal = true;
529                        matched_span = span;
530                        break;
531                    }
532                }
533            }
534            if matched_span > 0 {
535                i += matched_span;
536                continue;
537            }
538        }
539
540        // 4. AM/PM markers
541        if clean == "pm" || clean == "p.m" || loc.pm.contains(clean) {
542            ampm = Some(true);
543            i += 1;
544            continue;
545        }
546        if clean == "am" || clean == "a.m" || loc.am.contains(clean) {
547            ampm = Some(false);
548            i += 1;
549            continue;
550        }
551
552        // 5. Weekday name: match up to 4-word phrases -> unigram
553        if weekday_seen.is_none() {
554            let mut matched_span = 0usize;
555            for span in (1..=4).rev() {
556                if i + span <= raw_tokens.len() {
557                    let cand = if span == 1 {
558                        clean.to_string()
559                    } else {
560                        let mut s = String::from(clean);
561                        for k in 1..span {
562                            s.push(' ');
563                            s.push_str(raw_tokens[i + k].trim_matches(','));
564                        }
565                        s
566                    };
567                    if let Some(wd) = lookup_weekday(&cand, loc, settings.normalize) {
568                        weekday_seen = Some(wd);
569                        matched_locale_signal = true;
570                        matched_span = span;
571                        break;
572                    }
573                }
574            }
575            if matched_span > 0 {
576                i += matched_span;
577                continue;
578            }
579        }
580
581        // 6. Time-of-day word on absolute date ("12 December 2025 morning")
582        if time.is_none() {
583            if i + 1 < raw_tokens.len() {
584                let bigram = format!("{} {}", clean, raw_tokens[i + 1].trim_matches(','));
585                if let Some(h) = lookup_tod_hour(&bigram, loc, settings.normalize) {
586                    let (t, pod) = tod_hour_to_time_and_pod(h, settings);
587                    time = Some(t);
588                    part_of_day = pod;
589                    i += 2;
590                    continue;
591                }
592            }
593            if let Some(h) = lookup_tod_hour(clean, loc, settings.normalize) {
594                let (t, pod) = tod_hour_to_time_and_pod(h, settings);
595                time = Some(t);
596                part_of_day = pod;
597                i += 1;
598                continue;
599            }
600        }
601
602        // 6b. Apostrophe 2-digit year (e.g. "Nov 26 '26", "15 Jan ’99")
603        if year.is_none() {
604            if let Some(rest) = clean
605                .strip_prefix('\'')
606                .or_else(|| clean.strip_prefix('\u{2019}'))
607                .or_else(|| clean.strip_prefix('\u{2018}'))
608            {
609                if rest.len() == 2 && rest.bytes().all(|b| b.is_ascii_digit()) {
610                    if let Ok(y2) = rest.parse::<u32>() {
611                        year = Some(expand_two_digit_year(y2));
612                        i += 1;
613                        continue;
614                    }
615                }
616            }
617        }
618
619        // 7. Numeric token (including ordinals)
620        if let Some((num, digit_len)) = parse_date_number_or_ordinal(clean) {
621            if digit_len == 4 && (1000..=2999).contains(&num) && year.is_none() {
622                year = Some(num as i32);
623            } else {
624                free_nums.push((num, digit_len));
625            }
626            i += 1;
627            continue;
628        }
629
630        // 8. Skip / connector words (including localized "year" markers & locale-gated European connectors)
631        if loc.skip.contains(clean)
632            || loc.units.contains_key(clean)
633            || is_locale_connector(loc.code.as_str(), clean)
634            || matches!(
635                clean,
636                "at" | "on" | "of" | "the" | "in" | "de" | "del" | "el" | "la" | "le" | "à"
637                    | "am" | "um" | "den" | "saat" | "tarih" | "tarihinde" | "в" | "г" | "года"
638                    | "год" | "günü" | "gunu" | "yılında" | "yilinda" | "yılı" | "year" | "klo"
639                    | "u" | "у" | "سنة" | "år"
640            )
641        {
642            i += 1;
643            continue;
644        }
645
646        return None;
647    }
648
649    if !matched_locale_signal && year.is_none() {
650        return None;
651    }
652
653    let has_time = time.is_some();
654    if let (Some(t), Some(is_pm)) = (time, ampm) {
655        let mut h = t.hour();
656        if is_pm && h >= 1 && h < 12 {
657            h += 12;
658        } else if !is_pm && h == 12 {
659            h = 0;
660        }
661        time = NaiveTime::from_hms_nano_opt(h, t.minute(), t.second(), t.nanosecond());
662    }
663
664    let year_first = year.is_some()
665        && raw_tokens
666            .first()
667            .and_then(|t| parse_date_number_or_ordinal(t))
668            .map(|(n, l)| l == 4 && n as i32 == year.unwrap())
669            .unwrap_or(false);
670
671    let order = if settings.date_order.is_some() || settings.region.is_some() {
672        settings.effective_date_order(loc.date_order)
673    } else if year_first {
674        DateOrder::YMD
675    } else if settings.prefer_locale_date_order {
676        loc.date_order
677    } else {
678        DateOrder::MDY
679    };
680
681    match free_nums.as_slice() {
682        [] => {}
683        [(n, len)] => {
684            if month.is_some() && day.is_none() && (1..=31).contains(n) && *len <= 2 {
685                day = Some(*n);
686            } else if year.is_none() && *len == 2 {
687                year = Some(expand_two_digit_year(*n));
688            } else {
689                return None;
690            }
691        }
692        [(n1, l1), (n2, l2)] => {
693            if month.is_some() && day.is_none() && year.is_none() {
694                if (1..=31).contains(n1) && *l1 <= 2 && *l2 == 2 {
695                    day = Some(*n1);
696                    year = Some(expand_two_digit_year(*n2));
697                } else if (1..=31).contains(n2) && *l2 <= 2 && *l1 == 2 {
698                    year = Some(expand_two_digit_year(*n1));
699                    day = Some(*n2);
700                } else if (1..=31).contains(n1) && (1..=31).contains(n2) && n1 <= n2 {
701                    // Range without year: "June 12-14"
702                    day = Some(*n1);
703                } else {
704                    return None;
705                }
706            } else if month.is_some() && year.is_some() && day.is_none() && (1..=31).contains(n1) && (1..=31).contains(n2) && n1 <= n2 {
707                // Date range like "June 12-14, 2021" or "12-14 June 2021" -> take start day
708                day = Some(*n1);
709            } else if month.is_none() && day.is_none() {
710                match order {
711                    DateOrder::YMD | DateOrder::MDY if (1..=12).contains(n1) && (1..=31).contains(n2) => {
712                        month = Some(*n1);
713                        day = Some(*n2);
714                    }
715                    DateOrder::YMD | DateOrder::MDY if settings.strict_date_order == StrictDateOrder::All => {
716                        return None;
717                    }
718                    _ if (1..=31).contains(n1) && (1..=12).contains(n2) => {
719                        day = Some(*n1);
720                        month = Some(*n2);
721                    }
722                    _ if settings.strict_date_order == StrictDateOrder::All => {
723                        return None;
724                    }
725                    _ if (1..=12).contains(n1) && (1..=31).contains(n2) => {
726                        month = Some(*n1);
727                        day = Some(*n2);
728                    }
729                    _ => return None,
730                }
731            } else {
732                return None;
733            }
734        }
735        _ => return None,
736    }
737
738    if year.is_none() && month.is_none() && day.is_none() {
739        let wd = weekday_seen?;
740        if settings.strict_parsing
741            || settings.require_parts.contains(&DatePart::Year)
742            || settings.require_parts.contains(&DatePart::Month)
743            || settings.require_parts.contains(&DatePart::Day)
744        {
745            return None;
746        }
747        let base = settings.effective_base();
748        let cur_wd = base.weekday().num_days_from_monday() as i64;
749        let tgt_wd = wd as i64;
750        let diff = match settings.prefer_dates_from {
751            PreferDatesFrom::Past | PreferDatesFrom::CurrentPeriod => {
752                let mut d = tgt_wd - cur_wd;
753                if d > 0 {
754                    d -= 7;
755                }
756                d
757            }
758            PreferDatesFrom::Future => {
759                let mut d = tgt_wd - cur_wd;
760                if d < 0 {
761                    d += 7;
762                }
763                d
764            }
765        };
766        let target_date = base.date() + chrono::Duration::days(diff);
767        let nt = time.unwrap_or_else(|| NaiveTime::from_hms_opt(0, 0, 0).unwrap());
768        let mut p = vec!["year", "month", "day"];
769        if has_time {
770            p.push("time");
771        }
772        return Some(AbsoluteMatch {
773            naive: target_date.and_time(nt),
774            period: Period::Day,
775            locale: loc.code.clone(),
776            has_time,
777            parts: p,
778            part_of_day,
779        });
780    }
781
782    let base = settings.effective_base();
783    let (y, m, d, period, parts) =
784        complete_partial_date(year, month, day, has_time, base, settings)?;
785    let nd = NaiveDate::from_ymd_opt(y, m, d)?;
786    let nt = time.unwrap_or_else(|| NaiveTime::from_hms_opt(0, 0, 0).unwrap());
787
788    Some(AbsoluteMatch {
789        naive: nd.and_time(nt),
790        period,
791        locale: loc.code.clone(),
792        has_time,
793        parts,
794        part_of_day,
795    })
796}
797
798fn complete_partial_date(
799    year: Option<i32>,
800    month: Option<u32>,
801    day: Option<u32>,
802    has_time: bool,
803    base: NaiveDateTime,
804    settings: &Settings,
805) -> Option<(i32, u32, u32, Period, Vec<&'static str>)> {
806    if settings.strict_parsing && (year.is_none() || month.is_none() || day.is_none()) {
807        return None;
808    }
809    if settings.require_parts.contains(&DatePart::Year) && year.is_none() {
810        return None;
811    }
812    if settings.require_parts.contains(&DatePart::Month) && month.is_none() {
813        return None;
814    }
815    if settings.require_parts.contains(&DatePart::Day) && day.is_none() {
816        return None;
817    }
818
819    let period = if day.is_some() {
820        Period::Day
821    } else if month.is_some() {
822        Period::Month
823    } else {
824        Period::Year
825    };
826
827    let mut parts = Vec::with_capacity(4);
828    if year.is_some() {
829        parts.push("year");
830    }
831    if month.is_some() {
832        parts.push("month");
833    }
834    if day.is_some() {
835        parts.push("day");
836    }
837    if has_time {
838        parts.push("time");
839    }
840
841    let m = month.unwrap_or_else(|| match settings.prefer_month_of_year {
842        PreferMonthOfYear::First => 1,
843        PreferMonthOfYear::Last => 12,
844        PreferMonthOfYear::Current => base.month(),
845    });
846    if !(1..=12).contains(&m) {
847        return None;
848    }
849
850    let mut y = year.unwrap_or_else(|| base.year());
851    let d = day.unwrap_or_else(|| resolve_missing_day(y, m, base.day(), settings.prefer_day_of_month));
852    if d < 1 || d > days_in_month(y, m) {
853        return None;
854    }
855
856    if year.is_none() {
857        if let Some(cand) = NaiveDate::from_ymd_opt(y, m, d) {
858            match settings.prefer_dates_from {
859                PreferDatesFrom::Past if cand > base.date() => y -= 1,
860                PreferDatesFrom::Future if cand < base.date() => y += 1,
861                _ => {}
862            }
863        }
864    }
865
866    let final_d = d.min(days_in_month(y, m));
867    Some((y, m, final_d, period, parts))
868}
869
870fn split_date_tokens<'a>(s: &'a str, loc: &CompiledLocale, normalize: bool) -> Vec<&'a str> {
871    let mut out = Vec::with_capacity(8);
872    for chunk in s.split(|c: char| {
873        c.is_whitespace() || c == ',' || c == '/' || c == '[' || c == ']' || c == '–' || c == '—'
874    }) {
875        if chunk.is_empty() {
876            continue;
877        }
878        // Split dot-separated month expressions like "08.Haziran.2014" or "2005г.", but keep fractional times like "13:11:23.678" intact
879        if chunk.contains('.')
880            && !chunk.contains(':')
881            && !chunk.ends_with("a.m.")
882            && !chunk.ends_with("p.m.")
883            && !(chunk.matches('.').count() == 1
884                && chunk.chars().all(|c| c.is_ascii_digit() || c == '.'))
885        {
886            let clean = chunk.trim_matches('.');
887            if lookup_month(clean, loc, normalize).is_some()
888                || lookup_weekday(clean, loc, normalize).is_some()
889            {
890                out.push(clean);
891                continue;
892            }
893            for sub in chunk.split('.') {
894                if !sub.is_empty() {
895                    push_splitting_attached_digits(sub, loc, normalize, &mut out);
896                }
897            }
898            continue;
899        }
900        if chunk.contains('-') {
901            let clean = chunk.trim_matches('.');
902            if lookup_month(clean, loc, normalize).is_some()
903                || lookup_weekday(clean, loc, normalize).is_some()
904                || loc.months.keys().any(|k| k.split_whitespace().any(|w| w == clean))
905            {
906                out.push(chunk);
907                continue;
908            }
909            for sub in chunk.split('-') {
910                if !sub.is_empty() {
911                    push_splitting_attached_digits(sub, loc, normalize, &mut out);
912                }
913            }
914        } else {
915            push_splitting_attached_digits(chunk, loc, normalize, &mut out);
916        }
917    }
918    out
919}
920
921#[inline]
922fn is_locale_connector(lang: &str, clean: &str) -> bool {
923    match lang {
924        "it" => matches!(clean, "il" | "alle" | "ore" | "nel" | "della" | "all" | "di" | "lo"),
925        "es" => matches!(clean, "a" | "las" | "al" | "horas"),
926        "pt" => matches!(clean, "às" | "as" | "em" | "no" | "na" | "dia" | "horas"),
927        "fr" => matches!(clean, "au" | "du" | "les" | "heures" | "vers"),
928        "nl" => matches!(clean, "op" | "om" | "uur"),
929        "pl" => matches!(clean, "dnia" | "o" | "godz" | "roku" | "r"),
930        "sv" | "nb" | "da" | "nn" => matches!(clean, "kl" | "klockan" | "klokken"),
931        _ => false,
932    }
933}
934
935fn push_splitting_attached_digits<'a>(
936    tok: &'a str,
937    loc: &CompiledLocale,
938    normalize: bool,
939    out: &mut Vec<&'a str>,
940) {
941    // Keep apostrophe 2-digit years ('26, ’99), pure numbers, times, ordinals, and known month/weekday names intact
942    if let Some(rest) = tok
943        .strip_prefix('\'')
944        .or_else(|| tok.strip_prefix('\u{2019}'))
945        .or_else(|| tok.strip_prefix('\u{2018}'))
946    {
947        if rest.len() == 2 && rest.bytes().all(|b| b.is_ascii_digit()) {
948            out.push(tok);
949            return;
950        }
951    }
952    if tok.contains(':')
953        || tok.ends_with("am")
954        || tok.ends_with("pm")
955        || tok.ends_with("a.m.")
956        || tok.ends_with("p.m.")
957        || tok.bytes().all(|b| b.is_ascii_digit())
958        || parse_date_number_or_ordinal(tok).is_some()
959        || lookup_month(tok, loc, normalize).is_some()
960        || lookup_weekday(tok, loc, normalize).is_some()
961    {
962        out.push(tok);
963        return;
964    }
965    // Check if token mixes digits and non-digits (e.g. "2005г", "12Dec2025")
966    let has_digit = tok.chars().any(|c| c.is_ascii_digit());
967    let has_alpha = tok.chars().any(|c| c.is_alphabetic());
968    if !has_digit || !has_alpha {
969        out.push(tok);
970        return;
971    }
972    // Keep French/European "14h30" intact
973    if tok.contains('h') && tok.chars().all(|c| c.is_ascii_digit() || c == 'h' || c == 'm' || c == 's') {
974        out.push(tok);
975        return;
976    }
977    let mut start = 0usize;
978    let mut prev_digit = tok.chars().next().unwrap().is_ascii_digit();
979    for (idx, ch) in tok.char_indices().skip(1) {
980        let cur_digit = ch.is_ascii_digit();
981        if cur_digit != prev_digit {
982            out.push(&tok[start..idx]);
983            start = idx;
984            prev_digit = cur_digit;
985        }
986    }
987    if start < tok.len() {
988        out.push(&tok[start..]);
989    }
990}
991
992fn parse_date_number_or_ordinal(s: &str) -> Option<(u32, usize)> {
993    if s.is_empty() || s.len() > 6 {
994        return None;
995    }
996    let stripped = s
997        .strip_suffix("st")
998        .or_else(|| s.strip_suffix("nd"))
999        .or_else(|| s.strip_suffix("rd"))
1000        .or_else(|| s.strip_suffix("th"))
1001        .or_else(|| s.strip_suffix("er"))
1002        .or_else(|| s.strip_suffix('º'))
1003        .or_else(|| s.strip_suffix('ª'))
1004        .unwrap_or(s);
1005
1006    if stripped.is_empty() || stripped.len() > 4 || !stripped.bytes().all(|b| b.is_ascii_digit()) {
1007        return None;
1008    }
1009    let val: u32 = stripped.parse().ok()?;
1010    Some((val, stripped.len()))
1011}