Skip to main content

dateoxide_core/
lib.rs

1pub mod absolute;
2pub mod calendars;
3pub mod fast_path;
4pub mod locale;
5pub mod relative;
6pub mod search;
7pub mod settings;
8pub mod time_spans;
9pub mod timezone;
10pub mod umm_al_qura;
11
12use locale::{normalize_digits_and_lower, LocaleRegistry};
13use rayon::prelude::*;
14use search::SearchMatch;
15use settings::{DateData, ParsedDateTime, ParserKind, Period, Settings};
16use timezone::{extract_trailing_timezone_with_abbrevs, finalize_datetime};
17
18/// Parse a date string using default settings.
19#[inline]
20pub fn parse(input: &str) -> Option<ParsedDateTime> {
21    parse_with_settings(input, &Settings::default())
22}
23
24/// Parse a date string using explicit `Settings`.
25#[inline]
26pub fn parse_with_settings(input: &str, settings: &Settings) -> Option<ParsedDateTime> {
27    get_date_data(input, settings).date_obj
28}
29
30fn strip_user_skip_tokens(input: &str, skip_tokens: &[String]) -> String {
31    let mut out = Vec::new();
32    for tok in input.split_whitespace() {
33        let clean = tok.trim_matches(|c: char| c == ',' || c == '.');
34        if skip_tokens
35            .iter()
36            .any(|sk| sk.eq_ignore_ascii_case(tok) || sk.eq_ignore_ascii_case(clean))
37        {
38            continue;
39        }
40        out.push(tok);
41    }
42    out.join(" ")
43}
44
45#[inline]
46fn apply_time_period(period: Period, has_time: bool, settings: &Settings) -> Period {
47    if settings.return_time_as_period && has_time {
48        Period::Time
49    } else {
50        period
51    }
52}
53
54/// Relative-only parser backing `dateparser.freshness_date_parser.FreshnessDateDataParser`.
55pub fn parse_freshness(input: &str, settings: &Settings) -> DateData {
56    let trimmed = input.trim();
57    if trimmed.is_empty() {
58        return DateData::empty();
59    }
60    let (without_tz, tz) =
61        extract_trailing_timezone_with_abbrevs(trimmed, &settings.timezone_abbreviations);
62    let normalized = normalize_digits_and_lower(without_tz);
63    if normalized.is_empty() {
64        return DateData::empty();
65    }
66    let registry = LocaleRegistry::global();
67    let tokens: Vec<&str> = normalized
68        .split(|c: char| c.is_whitespace() || c == ',' || c == '/')
69        .map(|t| t.trim_matches(|c: char| c == '.' || c == '(' || c == ')'))
70        .filter(|t| !t.is_empty())
71        .collect();
72    let candidates = registry.detect_candidates(
73        &normalized,
74        &tokens,
75        settings.languages.as_deref(),
76        &settings.default_languages,
77        settings.normalize,
78    );
79    if let Some(m) = relative::try_parse_relative(&normalized, &candidates, registry, settings) {
80        return DateData {
81            date_obj: Some(finalize_datetime(m.naive, tz, settings)),
82            period: apply_time_period(m.period, m.has_time, settings),
83            locale: Some(m.locale),
84            parts: m.parts,
85            part_of_day: m.part_of_day,
86        };
87    }
88    DateData::empty()
89}
90
91/// Full `dateparser.date.DateDataParser.get_date_data` equivalent returning
92/// `DateData { date_obj, period, locale, parts, part_of_day }`.
93pub fn get_date_data(input: &str, settings: &Settings) -> DateData {
94    let trimmed_raw = input.trim();
95    if trimmed_raw.is_empty() {
96        return DateData::empty();
97    }
98
99    let owned_cleaned;
100    let trimmed: &str = if settings.skip_tokens.is_empty() {
101        trimmed_raw
102    } else {
103        owned_cleaned = strip_user_skip_tokens(trimmed_raw, &settings.skip_tokens);
104        if owned_cleaned.trim().is_empty() {
105            return DateData::empty();
106        }
107        owned_cleaned.trim()
108    };
109
110    // 0. Custom user strptime formats (`date_formats`)
111    if let Some(m) = fast_path::try_custom_formats(trimmed, settings) {
112        return DateData {
113            date_obj: Some(finalize_datetime(m.naive, m.tz, settings)),
114            period: apply_time_period(m.period, m.has_time, settings),
115            locale: Some("en".to_string()),
116            parts: m.parts,
117            part_of_day: None,
118        };
119    }
120
121    // 1. Zero-regex, zero-allocation fast path
122    if let Some(m) = fast_path::try_fast_path(trimmed, settings) {
123        return DateData {
124            date_obj: Some(finalize_datetime(m.naive, m.tz, settings)),
125            period: apply_time_period(m.period, m.has_time, settings),
126            locale: Some("en".to_string()),
127            parts: m.parts,
128            part_of_day: None,
129        };
130    }
131
132    // 2. Peel off optional trailing timezone before natural-language normalization
133    let (without_tz, tz) =
134        extract_trailing_timezone_with_abbrevs(trimmed, &settings.timezone_abbreviations);
135    let normalized = normalize_digits_and_lower(without_tz);
136    if normalized.is_empty() {
137        return DateData::empty();
138    }
139
140    // Re-check fast path if Unicode digits (e.g. Arabic-Indic / Persian) were normalized to ASCII
141    if normalized.as_bytes()[0].is_ascii_digit() && normalized != without_tz {
142        if let Some(m) = fast_path::try_fast_path(&normalized, settings) {
143            return DateData {
144                date_obj: Some(finalize_datetime(m.naive, m.tz.or(tz), settings)),
145                period: apply_time_period(m.period, m.has_time, settings),
146                locale: Some("en".to_string()),
147                parts: m.parts,
148                part_of_day: None,
149            };
150        }
151    }
152
153    // 3. Lazy-load the compact 205-language registry and detect top candidates in O(tokens)
154    let registry = LocaleRegistry::global();
155    let mut tokens: Vec<&str> = Vec::with_capacity(8);
156    for chunk in normalized.split(|c: char| {
157        c.is_whitespace() || c == ',' || c == '/' || c == '[' || c == ']' || c == '–' || c == '—'
158    }) {
159        let clean = chunk.trim_matches(|c: char| matches!(c, '.' | '(' | ')' | '[' | ']'));
160        if clean.is_empty() {
161            continue;
162        }
163        if registry.token_to_langs.contains_key(clean) {
164            tokens.push(clean);
165            continue;
166        }
167        for sub in clean.split(['-', '.']) {
168            if sub.is_empty() {
169                continue;
170            }
171            if sub.chars().any(|c| c.is_ascii_digit()) && sub.chars().any(|c| c.is_alphabetic()) {
172                let mut start = 0usize;
173                let mut prev_d = sub.chars().next().unwrap().is_ascii_digit();
174                for (idx, ch) in sub.char_indices().skip(1) {
175                    let cur_d = ch.is_ascii_digit();
176                    if cur_d != prev_d {
177                        tokens.push(&sub[start..idx]);
178                        start = idx;
179                        prev_d = cur_d;
180                    }
181                }
182                if start < sub.len() {
183                    tokens.push(&sub[start..]);
184                }
185            } else {
186                tokens.push(sub);
187            }
188        }
189    }
190
191    let candidates = registry.detect_candidates(
192        &normalized,
193        &tokens,
194        settings.languages.as_deref(),
195        &settings.default_languages,
196        settings.normalize,
197    );
198
199    if candidates.is_empty() {
200        if settings.allows_parser(ParserKind::AbsoluteTime)
201            && (normalized.contains('年')
202                || normalized.contains('月')
203                || normalized.contains('日')
204                || normalized.contains('년')
205                || normalized.contains('월')
206                || normalized.contains('일'))
207        {
208            if let Some(m) = absolute::try_parse_absolute(&normalized, &[], registry, settings) {
209                return DateData {
210                    date_obj: Some(finalize_datetime(m.naive, tz, settings)),
211                    period: apply_time_period(m.period, m.has_time, settings),
212                    locale: Some(m.locale),
213                    parts: m.parts,
214                    part_of_day: m.part_of_day,
215                };
216            }
217        }
218        return ignore_surrounding_fallback(trimmed, settings);
219    }
220
221    // 4. Multilingual Relative Date Engine
222    if settings.allows_parser(ParserKind::RelativeTime) {
223        if let Some(m) = relative::try_parse_relative(&normalized, &candidates, registry, settings) {
224            return DateData {
225                date_obj: Some(finalize_datetime(m.naive, tz, settings)),
226                period: apply_time_period(m.period, m.has_time, settings),
227                locale: Some(m.locale),
228                parts: m.parts,
229                part_of_day: m.part_of_day,
230            };
231        }
232    }
233
234    // 5. Multilingual Absolute & Partial Date Engine
235    if settings.allows_parser(ParserKind::AbsoluteTime) {
236        if let Some(m) = absolute::try_parse_absolute(&normalized, &candidates, registry, settings) {
237            return DateData {
238                date_obj: Some(finalize_datetime(m.naive, tz, settings)),
239                period: apply_time_period(m.period, m.has_time, settings),
240                locale: Some(m.locale),
241                parts: m.parts,
242                part_of_day: m.part_of_day,
243            };
244        }
245    }
246
247    ignore_surrounding_fallback(trimmed, settings)
248}
249
250fn ignore_surrounding_fallback(trimmed: &str, settings: &Settings) -> DateData {
251    if !settings.ignore_surrounding_text {
252        return DateData::empty();
253    }
254    let mut inner = settings.clone();
255    inner.ignore_surrounding_text = false;
256    let found = search_dates_full(trimmed, &inner);
257    if let Some(first) = found.into_iter().next() {
258        return DateData {
259            date_obj: Some(first.date_obj),
260            period: first.period,
261            locale: first.locale,
262            parts: vec!["year", "month", "day"],
263            part_of_day: None,
264        };
265    }
266    DateData::empty()
267}
268
269/// Parallel batch parsing powered by Rayon across all available CPU cores.
270pub fn parse_batch<S: AsRef<str> + Sync>(
271    inputs: &[S],
272    settings: &Settings,
273) -> Vec<Option<ParsedDateTime>> {
274    if inputs.len() < 256 {
275        return inputs
276            .iter()
277            .map(|s| parse_with_settings(s.as_ref(), settings))
278            .collect();
279    }
280    inputs
281        .par_iter()
282        .map(|s| parse_with_settings(s.as_ref(), settings))
283        .collect()
284}
285
286/// Find and parse all date expressions embedded in free-form text.
287pub fn search_dates(text: &str, settings: &Settings) -> Vec<(String, ParsedDateTime)> {
288    search::search_dates(text, settings)
289}
290
291/// Find and parse all date expressions embedded in free-form text, including detected locale code.
292pub fn search_dates_with_locale(
293    text: &str,
294    settings: &Settings,
295) -> Vec<(String, ParsedDateTime, Option<String>)> {
296    search::search_dates_with_locale(text, settings)
297}
298
299/// Find and parse all date expressions returning full match metadata.
300pub fn search_dates_full(text: &str, settings: &Settings) -> Vec<SearchMatch> {
301    search::search_dates_full(text, settings)
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307    use chrono::{NaiveDate, NaiveDateTime, NaiveTime, Timelike};
308    use settings::{DateOrder, PartOfDay, PreferDatesFrom, PreferDayOfMonth, StrictDateOrder};
309
310    fn fixed_settings() -> Settings {
311        Settings {
312            relative_base: Some(
313                NaiveDate::from_ymd_opt(2026, 11, 26)
314                    .unwrap()
315                    .and_hms_opt(15, 0, 0)
316                    .unwrap(),
317            ),
318            ..Default::default()
319        }
320    }
321
322    #[test]
323    fn test_fast_path_and_strict_date_order() {
324        let mut s = fixed_settings();
325        s.date_order = Some(DateOrder::MDY);
326        s.strict_date_order = StrictDateOrder::None;
327        assert_eq!(
328            parse_with_settings("26/11/2026", &s).unwrap().naive_local().date(),
329            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
330        );
331
332        s.strict_date_order = StrictDateOrder::All;
333        assert!(parse_with_settings("26/11/2026", &s).is_none());
334        assert_eq!(
335            parse_with_settings("2026/11/26", &s).unwrap().naive_local().date(),
336            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
337        );
338    }
339
340    #[test]
341    fn test_calendars_conversions() {
342        let s = fixed_settings();
343        assert_eq!(
344            calendars::jalali_to_gregorian(1395, 1, 1),
345            Some(NaiveDate::from_ymd_opt(2016, 3, 20).unwrap())
346        );
347        assert_eq!(
348            calendars::jalali_to_gregorian(1400, 1, 1),
349            Some(NaiveDate::from_ymd_opt(2021, 3, 21).unwrap())
350        );
351        assert_eq!(
352            calendars::jalali_to_gregorian(1404, 9, 5),
353            Some(NaiveDate::from_ymd_opt(2025, 11, 26).unwrap())
354        );
355        assert_eq!(
356            calendars::parse_jalali("۵ آذر ۱۴۰۴", &s).date_obj.unwrap().naive_local().date(),
357            NaiveDate::from_ymd_opt(2025, 11, 26).unwrap()
358        );
359
360        assert_eq!(
361            calendars::hijri_to_gregorian(1445, 1, 1),
362            Some(NaiveDate::from_ymd_opt(2023, 7, 19).unwrap())
363        );
364        assert_eq!(
365            calendars::hijri_to_gregorian(1446, 9, 1),
366            Some(NaiveDate::from_ymd_opt(2025, 3, 1).unwrap())
367        );
368
369        assert_eq!(
370            calendars::parse_minguo("115年11月26日", &s).date_obj.unwrap().naive_local().date(),
371            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
372        );
373
374        assert_eq!(
375            calendars::french_republican_to_gregorian(1, 1, 1),
376            Some(NaiveDate::from_ymd_opt(1792, 9, 22).unwrap())
377        );
378        assert_eq!(
379            calendars::parse_french_republican("14 Germinal an III", &s)
380                .date_obj
381                .unwrap()
382                .naive_local()
383                .date(),
384            NaiveDate::from_ymd_opt(1795, 4, 3).unwrap()
385        );
386    }
387
388    #[test]
389    fn test_parts_of_day_bare_durations_and_surrounding_text() {
390        let mut s = fixed_settings();
391        s.parts_of_day.morning = NaiveTime::from_hms_opt(8, 30, 0).unwrap();
392        let dd = get_date_data("yesterday morning", &s);
393        assert_eq!(
394            dd.date_obj.unwrap().naive_local(),
395            NaiveDate::from_ymd_opt(2026, 11, 25)
396                .unwrap()
397                .and_hms_opt(8, 30, 0)
398                .unwrap()
399        );
400        assert_eq!(dd.part_of_day, Some(PartOfDay::Morning));
401        assert_eq!(dd.parts, vec!["year", "month", "day", "time"]);
402
403        // Bare duration
404        let d_bare = parse_with_settings("2 days", &fixed_settings()).unwrap();
405        assert_eq!(d_bare.naive_local().date(), NaiveDate::from_ymd_opt(2026, 11, 24).unwrap());
406
407        // Week period
408        let dd_week = get_date_data("last week", &fixed_settings());
409        assert_eq!(dd_week.period, Period::Week);
410
411        // Ignore surrounding text
412        let mut s_ign = fixed_settings();
413        s_ign.ignore_surrounding_text = true;
414        assert_eq!(
415            parse_with_settings("Published: 12 December 2025", &s_ign)
416                .unwrap()
417                .naive_local()
418                .date(),
419            NaiveDate::from_ymd_opt(2025, 12, 12).unwrap()
420        );
421    }
422
423    #[test]
424    fn test_time_spans_and_custom_tz_abbrevs() {
425        let mut s = fixed_settings();
426        s.return_time_span = true;
427        let span_matches = search_dates_full("Show logs from last week please", &s);
428        assert_eq!(span_matches.len(), 2);
429
430        let mut s_tz = fixed_settings();
431        s_tz.timezone_abbreviations
432            .insert("FOO".to_string(), "+04:30".to_string());
433        s_tz.return_as_timezone_aware = Some(true);
434        let dt = parse_with_settings("2026-11-26 10:00 FOO", &s_tz).unwrap();
435        assert!(dt.is_aware());
436        assert_eq!(dt.naive_local().hour(), 10);
437    }
438
439    #[test]
440    fn test_timezone_conversion_and_preferences() {
441        let mut s = fixed_settings();
442        s.to_timezone = Some("Europe/Istanbul".to_string());
443        s.return_as_timezone_aware = Some(true);
444        let dt = parse_with_settings("2026-11-26T12:00:00Z", &s).unwrap();
445        assert_eq!(
446            dt.naive_local(),
447            NaiveDateTime::parse_from_str("2026-11-26 15:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
448        );
449
450        s.prefer_day_of_month = PreferDayOfMonth::First;
451        assert_eq!(
452            parse_with_settings("December 2025", &s).unwrap().naive_local().date(),
453            NaiveDate::from_ymd_opt(2025, 12, 1).unwrap()
454        );
455        s.prefer_dates_from = PreferDatesFrom::Past;
456        assert_eq!(
457            parse_with_settings("December 15", &s).unwrap().naive_local().date(),
458            NaiveDate::from_ymd_opt(2025, 12, 15).unwrap()
459        );
460    }
461}