Skip to main content

deep_time/alloc_parse/
parse_date.rs

1use crate::{
2    ClassifiedDate, DateClassification, Dt, DtErr, DtErrKind, Lang, Mode, Order, OrderFirst,
3    ParseCfg, STRTIME_SIZE, an_err, classify_date, default_date_parse_options,
4    generate_ambiguous_day_first_candidates, generate_ambiguous_month_first_candidates,
5    generate_ambiguous_year_first_candidates, generate_unambiguous_candidates,
6    is_week_date_missing_weekday, parse_pure_numeric_unix_timestamp, parse_syslog_no_year,
7    parse_week_date_no_weekday, parse_yyyy_mm, smart_detect_date_order, try_pure_numeric,
8};
9use alloc::borrow::Cow;
10use alloc::string::String;
11
12impl Dt {
13    /// Automatically parses datetime [`str`] into a [`Dt`] by guessing and generating the format. Supports the vast
14    /// majority of date formats.
15    ///
16    /// - Requires the `"parse"` feature (which enables `alloc`).
17    /// - The returned [`Dt`] is internally on the TAI time scale. The `attos` field is an [`i128`] attosecond
18    ///   count since TAI 2000-01-01 noon. See [`Scale`] for more information.
19    /// - The returned [`Dt`] is **not** in local time, if a timezone is parsed then it's used to find the offset
20    ///   to return non-local instant.
21    ///
22    /// ## Parameters
23    ///
24    /// - `s`: The string to parse. Must be non-empty and no longer than 255 bytes. Empty strings or overly
25    ///   long inputs return an error.
26    /// - `opts`: Optional [`ParseCfg`]. Pass `None` to use the defaults.
27    ///
28    /// ## Configuration Options
29    ///
30    /// These are the fields of the configuration options struct [`ParseCfg`], their types and defaults.
31    ///
32    /// See [`ParseCfg`] for more information.
33    ///
34    /// | Field          | Type and Default     | Effect |
35    /// |----------------|----------------------------------|--------|
36    /// | `lang`         | [`Lang::En`]                     | Language, scroll down to see currently supported languages                                        |
37    /// | `order`        | [`Order::Smart`]                 | How to resolve ambiguous numeric dates like `01/02/03`                                            |
38    /// | `mode`         | [`Mode::Auto`]                   | Special handling for purely numeric inputs                                                        |
39    /// | `parse`        | [`Option<Vec<String>>`] - `None` | An explicit list of formats to try, if the [`Mode`] is Explicit then only these formats are tried |
40    /// | `relative`     | [`bool`] - `true`                | Enable phrases like "tomorrow", "in 3 days"                   |
41    /// | `ref_time`     | [`Option<Dt>`] - `None`          | Reference time for relative dates and syslog-style "no-year" dates                                |
42    /// | `to_lower`     | [`bool`] - `true`                | Automatically lowercase the input, **only** set to false if it's already lowercase                |
43    ///
44    /// ## Purely Numeric Inputs
45    ///
46    /// When the input consists **only** of digits (and optionally a decimal point),
47    /// the parser uses a fast, mode-aware path before trying any other strategies.
48    /// The exact interpretation depends on the number of digits and the selected `mode`.
49    ///
50    /// | Digits | Example(s)               | `Mode`          | Interpreted as                          | Notes |
51    /// |--------|--------------------------|-----------------|-----------------------------------------|-------|
52    /// | 1–4    | `2024`, `24`, `5`        | `Auto`/`Legacy` | Year (2-digit uses 2000/1900 pivot)    | 1- and 3-digit years only work in `Scientific` |
53    /// | 5      | `24123`, `60400`         | `Legacy`        | Ordinal date (YYDDD)                    | — |
54    /// | 5      | `60400`, `60400.75`      | `Scientific`    | Modified Julian Date (MJD)              | Fractional days supported |
55    /// | 5      | `24123`, `60400.75`      | `Auto`          | Ordinal (non-decimal) or MJD (decimal) | Smart default |
56    /// | 6      | `240315`, `202403`       | `Auto`          | YYYYMM if plausible year, else YYMMDD   | Most common compact form |
57    /// | 6      | `240315`                 | `Legacy`        | YYMMDD preferred                        | — |
58    /// | 6      | `202403`                 | `Scientific`    | YYYYMM preferred                        | — |
59    /// | 7      | `2024123`                | `Legacy`        | Ordinal date (YYYYDDD)                  | — |
60    /// | 7      | `2460123`, `2460123.5`   | `Scientific`    | Julian Day (JD)                         | Fractional days supported |
61    /// | 7      | `2024123`                | `Auto`          | Ordinal (integer) or JD (decimal)       | Smart default |
62    /// | 10–11  | `1735689600`             | any             | Unix seconds                            | — |
63    /// | 12–15  | `1735689600123`          | any             | Unix milliseconds                       | Most common high-precision case |
64    /// | 16–18  | `1735689600123456`       | any             | Unix microseconds                       | — |
65    /// | 19+    | `1735689600123456789`    | any             | Unix nanoseconds                        | Full precision |
66    ///
67    /// Use `Mode::UnixTimestamp` when you know the input is always a Unix timestamp.
68    ///
69    /// ## Ambiguous Numeric Dates
70    ///
71    /// Dates where the components could map to different orders (e.g. `01/02/03`,
72    /// `3-4-5`, `15.03.24`, `2024.03.15`) are resolved via the `order` field:
73    ///
74    /// - **`Order::Smart`** (default) — Applies the fast heuristic described in [`Order::Smart`].
75    ///   It strongly prefers modern/tech conventions (Year-first for compact/ISO-like data)
76    ///   while handling the majority of international and US-style dates.
77    ///
78    /// - **`Order::Year`**, **`Order::Day`**, or **`Order::Month`** force a
79    ///   specific interpretation and bypass the heuristic entirely.
80    ///
81    /// ## Supported Formats
82    ///
83    /// The parser tokenizes known words (month/day names, relative phrases, timezones, etc.), generates candidate
84    /// formats from the token pattern, and tries them until one matches. Thousands of layouts are supported.
85    ///
86    /// Separators generally don't matter, they could be spaces, slashes, or hyphens, but **not colons** - colons are
87    /// reserved for the time connector, times, and offsets.
88    ///
89    /// Generally speaking the date part must come first, and stuff like time components, offsets and iana timezone names
90    /// must come afterwards.
91    ///
92    /// - **ISO 8601** and variants: `2024-03-15`, `2024-03-15T14:30:00Z`, `2024-03-15T14:30:00+01:00[Europe/Paris]`
93    /// - **Named dates** (in supported languages): `15 March 2024`, `15 mars 2024`, `15. März 2024`, `15 de marzo de 2024`
94    /// - **Week dates**: `2024-W15`, `2024-W15-3`, `2024W153` (missing weekday defaults to Monday)
95    /// - **Syslog-style** (no year): `Mar  5 10:23:45` (year inferred from `ref_time`)
96    /// - **Relative expressions**: `tomorrow`, `in 3 days`, `2 weeks ago`
97    /// - **12-hour time**: `2:30 PM`, `14:30:45.123`
98    /// - **Offsets and timezones**: `+0100`, `-05:30`, `Z`, IANA timezone names (with the `jiff-tz` feature enabled)
99    /// - **Library time scales**: `TAI`, `TT`, etc. are detected and parsed, must come after the date part of the input
100    ///
101    /// Relative dates are also automatically supported, except for bare numbers with no colons like `0900`, as these
102    /// are differently interpreted.
103    ///
104    /// ## Examples
105    ///
106    /// ```rust
107    /// use deep_time::{Dt, ParseCfg, Order, Mode, Lang, Scale};
108    ///
109    /// // Default smart parsing
110    /// let dt = Dt::from_str_parse("2024-03-15 14:30:00", &None).unwrap();
111    ///
112    /// // German named date
113    /// let cfg = ParseCfg { lang: Lang::De, ..Default::default() };
114    /// let dt = Dt::from_str_parse("15. März 2024 um 14:30", &Some(cfg)).unwrap();
115    ///
116    /// // Force month-first
117    /// let cfg = ParseCfg { order: Order::Month, ..Default::default() };
118    /// let dt = Dt::from_str_parse("03/15/2024", &Some(cfg)).unwrap();
119    ///
120    /// // Pure numeric compact form
121    /// let dt = Dt::from_str_parse("20240315", &None).unwrap(); // March 15, 2024
122    ///
123    /// // Unix timestamp (milliseconds)
124    /// let cfg = ParseCfg { mode: Mode::UnixTimestamp, ..Default::default() };
125    /// let dt = Dt::from_str_parse("1735689600123", &Some(cfg)).unwrap();
126    ///
127    /// // Explicit formats only (no fallback)
128    /// let cfg = ParseCfg {
129    ///     parse: Some(vec!["%d/%m/%Y".into(), "%Y-%m-%d".into()]),
130    ///     mode: Mode::Explicit,
131    ///     ..Default::default()
132    /// };
133    /// let dt = Dt::from_str_parse("15/03/2024", &Some(cfg)).unwrap();
134    ///
135    /// // Relative dates
136    /// let dt = Dt::from_str_parse("2 days from now", &None).unwrap();
137    ///
138    /// let ref_time = Dt::from_ymd(2026, 6, 16, Scale::UTC, 12, 0, 0, 0);
139    /// let en_cfg = Some(ParseCfg {
140    ///     ref_time: Some(ref_time),
141    ///     ..Default::default()
142    /// });
143    /// let dt = Dt::from_str_parse("next Monday at 14:00", &en_cfg).unwrap();
144    ///
145    /// assert_eq!(dt, Dt::from_ymd(2026, 6, 22, Scale::UTC, 14, 0, 0, 0));
146    /// ```
147    ///
148    /// ## Notes
149    ///
150    /// - The `Smart` + `Auto` combination gives the best real-world success rate for mixed data.
151    /// - Relative expressions and syslog-style no-year dates need a reference time. If `ref_time` is `None`
152    ///   and the `std` feature is enabled, system time is used; without `std`, set `ref_time` explicitly or
153    ///   parsing will fail.
154    /// - All successfully parsed [`Dt`] values are stored with attosecond precision on the internal
155    ///   TAI timescale.
156    /// - Timezone handling (IANA names and fixed offsets) is fully supported when the `jiff-tz` feature
157    ///   is enabled.
158    ///
159    /// ## Supported Languages:
160    ///
161    /// Language support here basically means supporting abbreviated and full day and month names.
162    /// Non-Ascii types of numeric characters are also supported such as full width digits.
163    ///
164    /// Some day/month names in non-English languages are not supported due to clashes, any such missing
165    /// support is noted below.
166    ///
167    /// - En
168    /// - De
169    ///     - Won't parse "t" as short form for day.
170    /// - Es
171    ///     - English word "ago" won't be detected as relative date word.
172    ///     - Won't parse "mar" as tuesday, will instead parse as march.
173    /// - Fr
174    ///     - Won't parse "mar" as tuesday, will instead parse as march.
175    ///
176    /// ## See also
177    ///
178    /// - [`ParseCfg`]
179    /// - [`Order`]
180    /// - [`Mode`]
181    /// - [`Lang`]
182    /// - [`Dt`]
183    /// - [`Dt::from_str_iso`](../struct.Dt.html#method.from_str_iso)
184    pub fn from_str_parse(s: &str, opts: &Option<ParseCfg>) -> Result<Dt, DtErr> {
185        let opts: &ParseCfg = opts
186            .as_ref()
187            .unwrap_or_else(|| default_date_parse_options());
188
189        if s.is_empty() {
190            return Err(an_err!(DtErrKind::Incomplete, "empty"));
191        } else if s.len() > STRTIME_SIZE {
192            return Err(an_err!(DtErrKind::InvalidInput, "too long: {}", s));
193        }
194
195        let lang: Lang = opts.lang;
196        let ref_time = &opts.ref_time;
197
198        let lowered: Cow<str> = if opts.to_lower {
199            Cow::Owned(s.to_lowercase())
200        } else {
201            Cow::Borrowed(s)
202        };
203
204        let classification = match classify_date(&lowered, lang, ref_time) {
205            Ok(ClassifiedDate::Parsed(time_point)) => return Ok(time_point),
206            Ok(ClassifiedDate::Cls(c)) => c,
207            Err(e) => {
208                // std::eprintln!("{}", e);
209                return Err(an_err!(
210                    DtErrKind::InvalidInput,
211                    "{}",
212                    s => e
213                ));
214            }
215        };
216
217        // let xx = &classification.date;
218        // if xx != trimmed {
219        //     eprintln!("NOT EQUAL: {:?}, {:?}", trimmed, xx);
220        // }
221        // eprintln!("BEFORE & AFTER: {:?}, {:?}", lowered, &classification.date);
222
223        let normalized = &classification.date;
224
225        let (mode, date_order) = if let Some(formats) = &opts.parse {
226            if !formats.is_empty() {
227                for fmt in formats {
228                    if let Ok(value) = Self::from_str(normalized, fmt, true, true, false) {
229                        return Ok(value);
230                    }
231                }
232                // None of the provided formats worked and mode is Explicit
233                if opts.mode == Mode::Explicit {
234                    return Err(an_err!(DtErrKind::InvalidInput, "{}", s));
235                }
236            }
237            (opts.mode, opts.order)
238        } else {
239            (opts.mode, opts.order)
240        };
241
242        // if s == "on the 5th of april 2024 at 00:00am" {
243        //     std::eprintln!("{:?}", classification);
244        // }
245        // std::eprintln!("{:?}", classification);
246
247        if classification.is_pure_numeric {
248            match mode {
249                Mode::UnixTimestamp => {
250                    if let Some(dt) = parse_pure_numeric_unix_timestamp(
251                        normalized,
252                        classification.num_non_decimal_digits as usize,
253                    ) {
254                        return Ok(dt);
255                    }
256                }
257                _ => {
258                    if let Some(dt) = try_pure_numeric(
259                        normalized,
260                        classification.num_digits,
261                        classification.num_non_decimal_digits,
262                        classification.is_decimal,
263                        mode,
264                    ) {
265                        // std::eprintln!("NUMERIC INPUT SUCCESS: {:?}", s);
266                        return Ok(dt);
267                    }
268                }
269            }
270        }
271        if !classification.has_year
272            && let Some(dt) = parse_syslog_no_year(normalized, lang, ref_time)
273        {
274            return Ok(dt);
275        }
276
277        if is_week_date_missing_weekday(&classification) {
278            // std::eprintln!("IS WEEK DATE MISSING WEEKDAY: {:?}", s);
279            if let Some(dt) = parse_week_date_no_weekday(&classification, lang, ref_time) {
280                return Ok(dt);
281            }
282        }
283        if let Some(dt) = try_unambiguous(normalized, &classification) {
284            return Ok(dt);
285        }
286        // std::eprintln!("done trying unambiguous");
287        if let Some(dt) = match date_order {
288            Order::Smart => {
289                let order = smart_detect_date_order(normalized, &classification);
290                let mut result: Option<Dt>;
291
292                match order {
293                    OrderFirst::Day => {
294                        result = try_compatible_formats(
295                            normalized,
296                            generate_ambiguous_day_first_candidates(&classification),
297                        );
298                        // std::eprintln!("done trying day first: {:?}", result);
299
300                        if result.is_none() {
301                            result = try_compatible_formats(
302                                normalized,
303                                generate_ambiguous_month_first_candidates(&classification),
304                            );
305                            // std::eprintln!("done trying month first: {:?}", result);
306                        }
307
308                        if result.is_none() {
309                            result = try_compatible_formats(
310                                normalized,
311                                generate_ambiguous_year_first_candidates(&classification),
312                            );
313                            // std::eprintln!("done trying year first: {:?}", result);
314                        }
315                    }
316                    OrderFirst::Month => {
317                        result = try_compatible_formats(
318                            normalized,
319                            generate_ambiguous_month_first_candidates(&classification),
320                        );
321                        // std::eprintln!("done trying month first: {:?}", result);
322
323                        if result.is_none() {
324                            result = try_compatible_formats(
325                                normalized,
326                                generate_ambiguous_day_first_candidates(&classification),
327                            );
328                            // std::eprintln!("done trying day first: {:?}", result);
329                        }
330
331                        if result.is_none() {
332                            result = try_compatible_formats(
333                                normalized,
334                                generate_ambiguous_year_first_candidates(&classification),
335                            );
336                            // std::eprintln!("done trying year first: {:?}", result);
337                        }
338                    }
339                    OrderFirst::Year => {
340                        result = try_compatible_formats(
341                            normalized,
342                            generate_ambiguous_year_first_candidates(&classification),
343                        );
344                        // std::eprintln!("done trying year first: {:?}", result);
345
346                        if result.is_none() {
347                            result = try_compatible_formats(
348                                normalized,
349                                generate_ambiguous_day_first_candidates(&classification),
350                            );
351                            // std::eprintln!("done trying day first: {:?}", result);
352                        }
353
354                        if result.is_none() {
355                            result = try_compatible_formats(
356                                normalized,
357                                generate_ambiguous_month_first_candidates(&classification),
358                            );
359                            // std::eprintln!("done trying month first: {:?}", result);
360                        }
361                    }
362                }
363
364                result
365            }
366            Order::Year => try_compatible_formats(
367                normalized,
368                generate_ambiguous_year_first_candidates(&classification),
369            ),
370            Order::Day => try_compatible_formats(
371                normalized,
372                generate_ambiguous_day_first_candidates(&classification),
373            ),
374            Order::Month => try_compatible_formats(
375                normalized,
376                generate_ambiguous_month_first_candidates(&classification),
377            ),
378        } {
379            return Ok(dt);
380        }
381        // std::eprintln!("NOW trying numeric timestamp");
382        if classification.is_pure_numeric
383            && mode != Mode::UnixTimestamp
384            && let Some(dt) = parse_pure_numeric_unix_timestamp(
385                normalized,
386                classification.num_non_decimal_digits as usize,
387            )
388        {
389            return Ok(dt);
390        }
391        Err(an_err!(DtErrKind::InvalidInput, "{}", s))
392    }
393
394    /// Same parsing logic as [`Dt::from_str_parse`](../struct.Dt.html#method.from_str_parse),
395    /// but returns attoseconds since the library epoch: 2000-01-01 12:00:00 UTC
396    /// (on the UTC scale).
397    ///
398    /// Returns `Some(attos)` on success (negative for pre-2000 dates) or `None`
399    /// on any parse error.
400    #[inline]
401    pub fn str_to_attos(s: &str, opts: &Option<ParseCfg>) -> Option<i128> {
402        Dt::from_str_parse(s, opts).ok().map(|tp| tp.to_attos())
403    }
404
405    /// Same parsing logic as [`Dt::from_str_parse`](../struct.Dt.html#method.from_str_parse),
406    /// but returns milliseconds since the library epoch: 2000-01-01 12:00:00 UTC
407    /// (on the UTC scale).
408    ///
409    /// Returns `Some(millis)` on success (negative for pre-2000 dates) or `None`
410    /// on any parse error.
411    #[inline]
412    pub fn str_to_ms(s: &str, opts: &Option<ParseCfg>) -> Option<i128> {
413        Dt::from_str_parse(s, opts).ok().map(|tp| tp.to_ms())
414    }
415
416    /// Same parsing logic as [`Dt::from_str_parse`](../struct.Dt.html#method.from_str_parse),
417    /// but returns nanoseconds since the library epoch: 2000-01-01 12:00:00 UTC
418    /// (on the UTC scale).
419    ///
420    /// Returns `Some(nanos)` on success (negative for pre-2000 dates) or `None`
421    /// on any parse error.
422    #[inline]
423    pub fn str_to_ns(s: &str, opts: &Option<ParseCfg>) -> Option<i128> {
424        Dt::from_str_parse(s, opts).ok().map(|tp| tp.to_ns())
425    }
426
427    /// Same parsing logic as [`Dt::from_str_parse`](../struct.Dt.html#method.from_str_parse),
428    /// but returns milliseconds since the UNIX epoch: (1970-01-01 00:00:00 UTC).
429    ///
430    /// Returns `Some(millis)` on success (negative for pre-2000 dates) or `None`
431    /// on any parse error.
432    #[inline]
433    pub fn str_to_unix_ms(s: &str, opts: &Option<ParseCfg>) -> Option<i128> {
434        Dt::from_str_parse(s, opts)
435            .ok()
436            .map(|tp| tp.to_scale_and_diff(Dt::UNIX_EPOCH, false).to_ms())
437    }
438
439    /// Same parsing logic as [`Dt::from_str_parse`](../struct.Dt.html#method.from_str_parse),
440    /// but returns nanoseconds since the UNIX epoch: (1970-01-01 00:00:00 UTC).
441    ///
442    /// Returns `Some(nanos)` on success (negative for pre-2000 dates) or `None`
443    /// on any parse error.
444    #[inline]
445    pub fn str_to_unix_ns(s: &str, opts: &Option<ParseCfg>) -> Option<i128> {
446        Dt::from_str_parse(s, opts)
447            .ok()
448            .map(|tp| tp.to_scale_and_diff(Dt::UNIX_EPOCH, false).to_ns())
449    }
450}
451
452/// Core zero-allocation helper (updated to match the new `&str` signature).
453///
454/// The `fmt` we get from the iterator is still `'static`, but it coerces automatically
455/// to `&str`, so everything continues to work.
456#[inline]
457pub(crate) fn try_compatible_formats<I>(s: &str, formats: I) -> Option<Dt>
458where
459    I: IntoIterator<Item = String>,
460{
461    // let mut dt = None;
462
463    // for fmt in formats.into_iter() {
464    //     eprintln!("TRYING FMT: {}", fmt);
465    //     dt = match Dt::from_str(s, &fmt, true, true, false) {
466    //         Ok(parsed) => Some(parsed),
467    //         Err(e) => {
468    //             eprintln!("  FAILED with: {:?}", e);
469    //             continue;
470    //         }
471    //     };
472    //     if dt.is_some() {
473    //         break;
474    //     }
475    //     // === DEBUG ===
476    //     // eprintln!("Tried format: {:?}", fmt);
477    // }
478
479    // dt
480    formats
481        .into_iter()
482        .find_map(|fmt| Dt::from_str(s, &fmt, true, true, false).ok())
483}
484
485#[inline]
486pub(crate) fn try_unambiguous(s: &str, classification: &DateClassification) -> Option<Dt> {
487    if matches!(classification.bytes_len, 6..=8)
488        && let Some(dt) = parse_yyyy_mm(s.as_bytes())
489    {
490        return Some(dt);
491    }
492    try_compatible_formats(s, generate_unambiguous_candidates(classification))
493}