1pub 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#[inline]
59pub fn parse(input: &str) -> Option<ParsedDateTime> {
60 parse_with_settings(input, &Settings::default())
61}
62
63#[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
93pub 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
130pub 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 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 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 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 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 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 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 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
309pub 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
326pub fn search_dates(text: &str, settings: &Settings) -> Vec<(String, ParsedDateTime)> {
328 search::search_dates(text, settings)
329}
330
331pub 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
339pub 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 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 let dd_week = get_date_data("last week", &fixed_settings());
449 assert_eq!(dd_week.period, Period::Week);
450
451 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}