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