Skip to main content

dateoxide_core/
lib.rs

1//! High-performance, low-memory, zero-ReDoS multilingual natural-language date parser in pure Rust.
2//!
3//! `dateoxide-core` powers the Python package [`dateoxide`](https://pypi.org/project/dateoxide/)
4//! across 205 languages, non-Gregorian calendars (official Saudi Umm al-Qura Hijri,
5//! Jalali, Minguo, French Republican), time spans, and parallel batch parsing.
6//!
7//! # Quick Start
8//!
9//! ```
10//! use dateoxide_core::{calendars, parse, parse_batch, parse_with_settings, search::search_dates, settings::Settings};
11//! use chrono::{Datelike, NaiveDate, NaiveDateTime};
12//!
13//! // Fast ISO-8601, RFC-2822/3339, and ISO week date parsing
14//! let dt = parse("2026-11-26").unwrap();
15//! assert_eq!(dt.naive_local().date(), NaiveDate::from_ymd_opt(2026, 11, 26).unwrap());
16//!
17//! let iso_week = parse("2026-W48-4").unwrap();
18//! assert_eq!(iso_week.naive_local().date(), NaiveDate::from_ymd_opt(2026, 11, 26).unwrap());
19//!
20//! // Multilingual natural-language & relative parsing with fixed RELATIVE_BASE
21//! let mut settings = Settings::default();
22//! settings.relative_base = Some(
23//!     NaiveDateTime::parse_from_str("2026-11-26 15:00:00", "%Y-%m-%d %H:%M:%S").unwrap(),
24//! );
25//! let tr = parse_with_settings("3 gün önce", &settings).unwrap();
26//! assert_eq!(tr.naive_local().day(), 23);
27//!
28//! // Free-form text extraction and parallel batch parsing
29//! let found = search_dates("Meeting on 12 December 2025", &settings);
30//! assert_eq!(found.len(), 1);
31//!
32//! let batch = parse_batch(&["2026-11-26", "vor 2 Wochen", "not a date"], &settings);
33//! assert!(batch[0].is_some() && batch[1].is_some() && batch[2].is_none());
34//!
35//! // Non-Gregorian calendar conversion (official Umm al-Qura Hijri)
36//! let hijri = calendars::parse_hijri("1446/09/01", &settings);
37//! assert_eq!(hijri.date_obj.unwrap().naive_local().date(), NaiveDate::from_ymd_opt(2025, 3, 1).unwrap());
38//! ```
39
40pub mod absolute;
41pub mod calendars;
42pub mod fast_path;
43pub mod locale;
44pub mod relative;
45pub mod search;
46pub mod settings;
47pub mod time_spans;
48pub mod timezone;
49pub mod umm_al_qura;
50
51use locale::{normalize_digits_and_lower, LocaleRegistry};
52use rayon::prelude::*;
53use search::SearchMatch;
54use settings::{DateData, ParsedDateTime, ParserKind, Period, Settings};
55use timezone::{extract_trailing_timezone_with_abbrevs, finalize_datetime};
56
57/// Parse a date string using default settings.
58#[inline]
59pub fn parse(input: &str) -> Option<ParsedDateTime> {
60    parse_with_settings(input, &Settings::default())
61}
62
63/// Parse a date string using explicit `Settings`.
64#[inline]
65pub fn parse_with_settings(input: &str, settings: &Settings) -> Option<ParsedDateTime> {
66    get_date_data(input, settings).date_obj
67}
68
69fn strip_user_skip_tokens(input: &str, skip_tokens: &[String]) -> String {
70    let mut out = Vec::new();
71    for tok in input.split_whitespace() {
72        let clean = tok.trim_matches(|c: char| c == ',' || c == '.');
73        if skip_tokens
74            .iter()
75            .any(|sk| sk.eq_ignore_ascii_case(tok) || sk.eq_ignore_ascii_case(clean))
76        {
77            continue;
78        }
79        out.push(tok);
80    }
81    out.join(" ")
82}
83
84#[inline]
85fn apply_time_period(period: Period, has_time: bool, settings: &Settings) -> Period {
86    if settings.return_time_as_period && has_time {
87        Period::Time
88    } else {
89        period
90    }
91}
92
93/// Relative-only parser backing `dateparser.freshness_date_parser.FreshnessDateDataParser`.
94pub fn parse_freshness(input: &str, settings: &Settings) -> DateData {
95    let trimmed = input.trim();
96    if trimmed.is_empty() {
97        return DateData::empty();
98    }
99    let (without_tz, tz) =
100        extract_trailing_timezone_with_abbrevs(trimmed, &settings.timezone_abbreviations);
101    let normalized = normalize_digits_and_lower(without_tz);
102    if normalized.is_empty() {
103        return DateData::empty();
104    }
105    let registry = LocaleRegistry::global();
106    let tokens: Vec<&str> = normalized
107        .split(|c: char| c.is_whitespace() || c == ',' || c == '/')
108        .map(|t| t.trim_matches(|c: char| c == '.' || c == '(' || c == ')'))
109        .filter(|t| !t.is_empty())
110        .collect();
111    let candidates = registry.detect_candidates(
112        &normalized,
113        &tokens,
114        settings.languages.as_deref(),
115        &settings.default_languages,
116        settings.normalize,
117    );
118    if let Some(m) = relative::try_parse_relative(&normalized, &candidates, registry, settings) {
119        return DateData {
120            date_obj: Some(finalize_datetime(m.naive, tz, settings)),
121            period: apply_time_period(m.period, m.has_time, settings),
122            locale: Some(m.locale),
123            parts: m.parts,
124            part_of_day: m.part_of_day,
125        };
126    }
127    DateData::empty()
128}
129
130/// Full `dateparser.date.DateDataParser.get_date_data` equivalent returning
131/// `DateData { date_obj, period, locale, parts, part_of_day }`.
132pub fn get_date_data(input: &str, settings: &Settings) -> DateData {
133    let trimmed_raw = input.trim();
134    if trimmed_raw.is_empty() {
135        return DateData::empty();
136    }
137
138    let owned_cleaned;
139    let trimmed: &str = if settings.skip_tokens.is_empty() {
140        trimmed_raw
141    } else {
142        owned_cleaned = strip_user_skip_tokens(trimmed_raw, &settings.skip_tokens);
143        if owned_cleaned.trim().is_empty() {
144            return DateData::empty();
145        }
146        owned_cleaned.trim()
147    };
148
149    // 0. Custom user strptime formats (`date_formats`)
150    if let Some(m) = fast_path::try_custom_formats(trimmed, settings) {
151        return DateData {
152            date_obj: Some(finalize_datetime(m.naive, m.tz, settings)),
153            period: apply_time_period(m.period, m.has_time, settings),
154            locale: Some("en".to_string()),
155            parts: m.parts,
156            part_of_day: None,
157        };
158    }
159
160    // 1. Zero-regex, zero-allocation fast path
161    if let Some(m) = fast_path::try_fast_path(trimmed, settings) {
162        return DateData {
163            date_obj: Some(finalize_datetime(m.naive, m.tz, settings)),
164            period: apply_time_period(m.period, m.has_time, settings),
165            locale: Some("en".to_string()),
166            parts: m.parts,
167            part_of_day: None,
168        };
169    }
170
171    // 2. Peel off optional trailing timezone before natural-language normalization
172    let (without_tz, tz) =
173        extract_trailing_timezone_with_abbrevs(trimmed, &settings.timezone_abbreviations);
174    let normalized = normalize_digits_and_lower(without_tz);
175    if normalized.is_empty() {
176        return DateData::empty();
177    }
178
179    // Re-check fast path if Unicode digits (e.g. Arabic-Indic / Persian) were normalized to ASCII
180    if normalized.as_bytes()[0].is_ascii_digit() && normalized != without_tz {
181        if let Some(m) = fast_path::try_fast_path(&normalized, settings) {
182            return DateData {
183                date_obj: Some(finalize_datetime(m.naive, m.tz.or(tz), settings)),
184                period: apply_time_period(m.period, m.has_time, settings),
185                locale: Some("en".to_string()),
186                parts: m.parts,
187                part_of_day: None,
188            };
189        }
190    }
191
192    // 3. Lazy-load the compact 205-language registry and detect top candidates in O(tokens)
193    let registry = LocaleRegistry::global();
194    let mut tokens: Vec<&str> = Vec::with_capacity(8);
195    for chunk in normalized.split(|c: char| {
196        c.is_whitespace() || c == ',' || c == '/' || c == '[' || c == ']' || c == '–' || c == '—'
197    }) {
198        let clean = chunk.trim_matches(|c: char| matches!(c, '.' | '(' | ')' | '[' | ']'));
199        if clean.is_empty() {
200            continue;
201        }
202        if registry.token_to_langs.contains_key(clean) {
203            tokens.push(clean);
204            continue;
205        }
206        for sub in clean.split(['-', '.']) {
207            if sub.is_empty() {
208                continue;
209            }
210            if sub.chars().any(|c| c.is_ascii_digit()) && sub.chars().any(|c| c.is_alphabetic()) {
211                let mut start = 0usize;
212                let mut prev_d = sub.chars().next().unwrap().is_ascii_digit();
213                for (idx, ch) in sub.char_indices().skip(1) {
214                    let cur_d = ch.is_ascii_digit();
215                    if cur_d != prev_d {
216                        tokens.push(&sub[start..idx]);
217                        start = idx;
218                        prev_d = cur_d;
219                    }
220                }
221                if start < sub.len() {
222                    tokens.push(&sub[start..]);
223                }
224            } else {
225                tokens.push(sub);
226            }
227        }
228    }
229
230    let candidates = registry.detect_candidates(
231        &normalized,
232        &tokens,
233        settings.languages.as_deref(),
234        &settings.default_languages,
235        settings.normalize,
236    );
237
238    if candidates.is_empty() {
239        let is_cjk_or_bare_year = (normalized.len() == 4
240            && normalized.bytes().all(|b| b.is_ascii_digit()))
241            || normalized.contains('年')
242            || normalized.contains('月')
243            || normalized.contains('日')
244            || normalized.contains('년')
245            || normalized.contains('월')
246            || normalized.contains('일');
247        if settings.allows_parser(ParserKind::AbsoluteTime) && is_cjk_or_bare_year {
248            if let Some(m) = absolute::try_parse_absolute(&normalized, &[], registry, settings) {
249                return DateData {
250                    date_obj: Some(finalize_datetime(m.naive, tz, settings)),
251                    period: apply_time_period(m.period, m.has_time, settings),
252                    locale: Some(m.locale),
253                    parts: m.parts,
254                    part_of_day: m.part_of_day,
255                };
256            }
257        }
258        return ignore_surrounding_fallback(trimmed, settings);
259    }
260
261    // 4. Multilingual Relative Date Engine
262    if settings.allows_parser(ParserKind::RelativeTime) {
263        if let Some(m) = relative::try_parse_relative(&normalized, &candidates, registry, settings) {
264            return DateData {
265                date_obj: Some(finalize_datetime(m.naive, tz, settings)),
266                period: apply_time_period(m.period, m.has_time, settings),
267                locale: Some(m.locale),
268                parts: m.parts,
269                part_of_day: m.part_of_day,
270            };
271        }
272    }
273
274    // 5. Multilingual Absolute & Partial Date Engine
275    if settings.allows_parser(ParserKind::AbsoluteTime) {
276        if let Some(m) = absolute::try_parse_absolute(&normalized, &candidates, registry, settings) {
277            return DateData {
278                date_obj: Some(finalize_datetime(m.naive, tz, settings)),
279                period: apply_time_period(m.period, m.has_time, settings),
280                locale: Some(m.locale),
281                parts: m.parts,
282                part_of_day: m.part_of_day,
283            };
284        }
285    }
286
287    ignore_surrounding_fallback(trimmed, settings)
288}
289
290fn ignore_surrounding_fallback(trimmed: &str, settings: &Settings) -> DateData {
291    if !settings.ignore_surrounding_text {
292        return DateData::empty();
293    }
294    let mut inner = settings.clone();
295    inner.ignore_surrounding_text = false;
296    let found = search_dates_full(trimmed, &inner);
297    if let Some(first) = found.into_iter().next() {
298        return DateData {
299            date_obj: Some(first.date_obj),
300            period: first.period,
301            locale: first.locale,
302            parts: vec!["year", "month", "day"],
303            part_of_day: None,
304        };
305    }
306    DateData::empty()
307}
308
309/// Parallel batch parsing powered by Rayon across all available CPU cores.
310pub fn parse_batch<S: AsRef<str> + Sync>(
311    inputs: &[S],
312    settings: &Settings,
313) -> Vec<Option<ParsedDateTime>> {
314    if inputs.len() < 256 {
315        return inputs
316            .iter()
317            .map(|s| parse_with_settings(s.as_ref(), settings))
318            .collect();
319    }
320    inputs
321        .par_iter()
322        .map(|s| parse_with_settings(s.as_ref(), settings))
323        .collect()
324}
325
326/// Find and parse all date expressions embedded in free-form text.
327pub fn search_dates(text: &str, settings: &Settings) -> Vec<(String, ParsedDateTime)> {
328    search::search_dates(text, settings)
329}
330
331/// Find and parse all date expressions embedded in free-form text, including detected locale code.
332pub fn search_dates_with_locale(
333    text: &str,
334    settings: &Settings,
335) -> Vec<(String, ParsedDateTime, Option<String>)> {
336    search::search_dates_with_locale(text, settings)
337}
338
339/// Find and parse all date expressions returning full match metadata.
340pub fn search_dates_full(text: &str, settings: &Settings) -> Vec<SearchMatch> {
341    search::search_dates_full(text, settings)
342}
343
344#[cfg(test)]
345mod tests {
346    use super::*;
347    use chrono::{NaiveDate, NaiveDateTime, NaiveTime, Timelike};
348    use settings::{DateOrder, PartOfDay, PreferDatesFrom, PreferDayOfMonth, StrictDateOrder};
349
350    fn fixed_settings() -> Settings {
351        Settings {
352            relative_base: Some(
353                NaiveDate::from_ymd_opt(2026, 11, 26)
354                    .unwrap()
355                    .and_hms_opt(15, 0, 0)
356                    .unwrap(),
357            ),
358            ..Default::default()
359        }
360    }
361
362    #[test]
363    fn test_fast_path_and_strict_date_order() {
364        let mut s = fixed_settings();
365        s.date_order = Some(DateOrder::MDY);
366        s.strict_date_order = StrictDateOrder::None;
367        assert_eq!(
368            parse_with_settings("26/11/2026", &s).unwrap().naive_local().date(),
369            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
370        );
371
372        s.strict_date_order = StrictDateOrder::All;
373        assert!(parse_with_settings("26/11/2026", &s).is_none());
374        assert_eq!(
375            parse_with_settings("2026/11/26", &s).unwrap().naive_local().date(),
376            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
377        );
378    }
379
380    #[test]
381    fn test_calendars_conversions() {
382        let s = fixed_settings();
383        assert_eq!(
384            calendars::jalali_to_gregorian(1395, 1, 1),
385            Some(NaiveDate::from_ymd_opt(2016, 3, 20).unwrap())
386        );
387        assert_eq!(
388            calendars::jalali_to_gregorian(1400, 1, 1),
389            Some(NaiveDate::from_ymd_opt(2021, 3, 21).unwrap())
390        );
391        assert_eq!(
392            calendars::jalali_to_gregorian(1404, 9, 5),
393            Some(NaiveDate::from_ymd_opt(2025, 11, 26).unwrap())
394        );
395        assert_eq!(
396            calendars::parse_jalali("۵ آذر ۱۴۰۴", &s).date_obj.unwrap().naive_local().date(),
397            NaiveDate::from_ymd_opt(2025, 11, 26).unwrap()
398        );
399
400        assert_eq!(
401            calendars::hijri_to_gregorian(1445, 1, 1),
402            Some(NaiveDate::from_ymd_opt(2023, 7, 19).unwrap())
403        );
404        assert_eq!(
405            calendars::hijri_to_gregorian(1446, 9, 1),
406            Some(NaiveDate::from_ymd_opt(2025, 3, 1).unwrap())
407        );
408
409        assert_eq!(
410            calendars::parse_minguo("115年11月26日", &s).date_obj.unwrap().naive_local().date(),
411            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
412        );
413
414        assert_eq!(
415            calendars::french_republican_to_gregorian(1, 1, 1),
416            Some(NaiveDate::from_ymd_opt(1792, 9, 22).unwrap())
417        );
418        assert_eq!(
419            calendars::parse_french_republican("14 Germinal an III", &s)
420                .date_obj
421                .unwrap()
422                .naive_local()
423                .date(),
424            NaiveDate::from_ymd_opt(1795, 4, 3).unwrap()
425        );
426    }
427
428    #[test]
429    fn test_parts_of_day_bare_durations_and_surrounding_text() {
430        let mut s = fixed_settings();
431        s.parts_of_day.morning = NaiveTime::from_hms_opt(8, 30, 0).unwrap();
432        let dd = get_date_data("yesterday morning", &s);
433        assert_eq!(
434            dd.date_obj.unwrap().naive_local(),
435            NaiveDate::from_ymd_opt(2026, 11, 25)
436                .unwrap()
437                .and_hms_opt(8, 30, 0)
438                .unwrap()
439        );
440        assert_eq!(dd.part_of_day, Some(PartOfDay::Morning));
441        assert_eq!(dd.parts, vec!["year", "month", "day", "time"]);
442
443        // Bare duration
444        let d_bare = parse_with_settings("2 days", &fixed_settings()).unwrap();
445        assert_eq!(d_bare.naive_local().date(), NaiveDate::from_ymd_opt(2026, 11, 24).unwrap());
446
447        // Week period
448        let dd_week = get_date_data("last week", &fixed_settings());
449        assert_eq!(dd_week.period, Period::Week);
450
451        // Ignore surrounding text
452        let mut s_ign = fixed_settings();
453        s_ign.ignore_surrounding_text = true;
454        assert_eq!(
455            parse_with_settings("Published: 12 December 2025", &s_ign)
456                .unwrap()
457                .naive_local()
458                .date(),
459            NaiveDate::from_ymd_opt(2025, 12, 12).unwrap()
460        );
461    }
462
463    #[test]
464    fn test_time_spans_and_custom_tz_abbrevs() {
465        let mut s = fixed_settings();
466        s.return_time_span = true;
467        let span_matches = search_dates_full("Show logs from last week please", &s);
468        assert_eq!(span_matches.len(), 2);
469
470        let mut s_tz = fixed_settings();
471        s_tz.timezone_abbreviations
472            .insert("FOO".to_string(), "+04:30".to_string());
473        s_tz.return_as_timezone_aware = Some(true);
474        let dt = parse_with_settings("2026-11-26 10:00 FOO", &s_tz).unwrap();
475        assert!(dt.is_aware());
476        assert_eq!(dt.naive_local().hour(), 10);
477    }
478
479    #[test]
480    fn test_timezone_conversion_and_preferences() {
481        let mut s = fixed_settings();
482        s.to_timezone = Some("Europe/Istanbul".to_string());
483        s.return_as_timezone_aware = Some(true);
484        let dt = parse_with_settings("2026-11-26T12:00:00Z", &s).unwrap();
485        assert_eq!(
486            dt.naive_local(),
487            NaiveDateTime::parse_from_str("2026-11-26 15:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
488        );
489
490        s.prefer_day_of_month = PreferDayOfMonth::First;
491        assert_eq!(
492            parse_with_settings("December 2025", &s).unwrap().naive_local().date(),
493            NaiveDate::from_ymd_opt(2025, 12, 1).unwrap()
494        );
495        s.prefer_dates_from = PreferDatesFrom::Past;
496        assert_eq!(
497            parse_with_settings("December 15", &s).unwrap().naive_local().date(),
498            NaiveDate::from_ymd_opt(2025, 12, 15).unwrap()
499        );
500    }
501
502    #[test]
503    fn test_iso_week_dates_and_year_zero_guard() {
504        let s = fixed_settings();
505        assert_eq!(
506            parse_with_settings("2026-W48-4", &s).unwrap().naive_local().date(),
507            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
508        );
509        assert_eq!(
510            parse_with_settings("2026-W48", &s).unwrap().naive_local().date(),
511            NaiveDate::from_ymd_opt(2026, 11, 23).unwrap()
512        );
513        assert_eq!(
514            parse_with_settings("2026W484", &s).unwrap().naive_local().date(),
515            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
516        );
517        assert!(parse_with_settings("2026-W54-1", &s).is_none());
518        assert!(parse_with_settings("0000-01-01", &s).is_none());
519
520        let mut s_strict = fixed_settings();
521        s_strict.strict_parsing = true;
522        assert!(parse_with_settings("2026-W48", &s_strict).is_none());
523    }
524
525    #[test]
526    fn test_no_spaces_time_and_time_only_preferences() {
527        let mut s_ns = fixed_settings();
528        s_ns.parsers = Some(vec![ParserKind::NoSpacesTime]);
529        assert_eq!(
530            parse_with_settings("1430", &s_ns).unwrap().naive_local(),
531            NaiveDate::from_ymd_opt(2026, 11, 26)
532                .unwrap()
533                .and_hms_opt(14, 30, 0)
534                .unwrap()
535        );
536        assert_eq!(
537            parse_with_settings("143025", &s_ns).unwrap().naive_local(),
538            NaiveDate::from_ymd_opt(2026, 11, 26)
539                .unwrap()
540                .and_hms_opt(14, 30, 25)
541                .unwrap()
542        );
543        s_ns.date_order = Some(DateOrder::DMY);
544        assert_eq!(
545            parse_with_settings("26112026", &s_ns).unwrap().naive_local().date(),
546            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
547        );
548        s_ns.date_order = Some(DateOrder::MDY);
549        assert_eq!(
550            parse_with_settings("11262026", &s_ns).unwrap().naive_local().date(),
551            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
552        );
553
554        let mut s_fut = fixed_settings();
555        s_fut.prefer_dates_from = PreferDatesFrom::Future;
556        assert_eq!(
557            parse_with_settings("09:00", &s_fut).unwrap().naive_local(),
558            NaiveDate::from_ymd_opt(2026, 11, 27)
559                .unwrap()
560                .and_hms_opt(9, 0, 0)
561                .unwrap()
562        );
563
564        let mut s_past = fixed_settings();
565        s_past.prefer_dates_from = PreferDatesFrom::Past;
566        assert_eq!(
567            parse_with_settings("18:00", &s_past).unwrap().naive_local(),
568            NaiveDate::from_ymd_opt(2026, 11, 25)
569                .unwrap()
570                .and_hms_opt(18, 0, 0)
571                .unwrap()
572        );
573    }
574
575    #[test]
576    fn test_search_dates_false_positive_guards() {
577        let s = fixed_settings();
578        let found = search_dates_full("Let us meet tomorrow at 5pm or next Friday.", &s);
579        assert!(!found.iter().any(|m| m.text == "Let"));
580        assert_eq!(found.len(), 2);
581
582        assert!(search_dates_full("She can see her man, did you say?", &s).is_empty());
583        assert!(search_dates_full("Python 3.12.1 on 192.168.1.1", &s).is_empty());
584    }
585}