Skip to main content

qsv_dateparser/
lib.rs

1//! A rust library for parsing date strings in commonly used formats. Parsed date will be returned
2//! as `chrono`'s `DateTime<Utc>`.
3//!
4//! # Quick Start
5//!
6//!
7//! Use `str`'s `parse` method:
8//!
9//! ```
10//! use chrono::prelude::*;
11//! use qsv_dateparser::DateTimeUtc;
12//! use std::error::Error;
13//!
14//! fn main() -> Result<(), Box<dyn Error>> {
15//!     assert_eq!(
16//!         "2021-05-14 18:51 PDT".parse::<DateTimeUtc>()?.0,
17//!         Utc.ymd(2021, 5, 15).and_hms(1, 51, 0),
18//!     );
19//!     Ok(())
20//! }
21//! ```
22//!
23//! ## Accepted date formats
24//!
25//! ```
26//! use qsv_dateparser::DateTimeUtc;
27//!
28//! let accepted = vec![
29//!     // unix timestamp
30//!     "1511648546",
31//!     "1620021848429",
32//!     "1620024872717915000",
33//!     "0",
34//!     "-770172300",
35//!     "1671673426.123456789",
36//!     // rfc3339
37//!     "2021-05-01T01:17:02.604456Z",
38//!     "2017-11-25T22:34:50Z",
39//!     // rfc2822
40//!     "Wed, 02 Jun 2021 06:31:39 GMT",
41//!     // yyyy-mm-dd hh:mm:ss
42//!     "2014-04-26 05:24:37 PM",
43//!     "2021-04-30 21:14",
44//!     "2021-04-30 21:14:10",
45//!     "2021-04-30 21:14:10.052282",
46//!     "2014-04-26 17:24:37.123",
47//!     "2014-04-26 17:24:37.3186369",
48//!     "2012-08-03 18:31:59.257000000",
49//!     "2020-01-15T08:00",
50//!     "2020-01-15T08:00:00",
51//!     "2020-01-15T08:00:00.123456",
52//!     "2012-03-19 10:11:59.318 PM",
53//!     "2012-03-19T10:11:59.318 PM",
54//!     // yyyy-mm-dd hh:mm:ss z
55//!     "2017-11-25 13:31:15 PST",
56//!     "2017-11-25 13:31 PST",
57//!     "2014-12-16 06:20:00 UTC",
58//!     "2014-12-16 06:20:00 GMT",
59//!     "2014-04-26 13:13:43 +0800",
60//!     "2014-04-26 13:13:44 +09:00",
61//!     "2012-08-03 18:31:59.257000000 +0000",
62//!     "2015-09-30 18:48:56.35272715 UTC",
63//!     "2021-05-14 18:51 PDT",
64//!     // yyyy-mm-dd
65//!     "2021-02-21",
66//!     // yyyy-mm-dd z
67//!     "2021-02-21 PST",
68//!     "2021-02-21 UTC",
69//!     "2020-07-20+08:00",
70//!     // Mon dd, yyyy, hh:mm:ss
71//!     "May 8, 2009 5:57:51 PM",
72//!     "September 17, 2012 10:09am",
73//!     "September 17, 2012, 10:10:09",
74//!     // Mon dd, yyyy hh:mm:ss z
75//!     "May 02, 2021 15:51:31 UTC",
76//!     "May 02, 2021 15:51 UTC",
77//!     "May 26, 2021, 12:49 AM PDT",
78//!     "September 17, 2012 at 10:09am PST",
79//!     // yyyy-mon-dd
80//!     "2021-Feb-21",
81//!     // Mon dd, yyyy
82//!     "May 25, 2021",
83//!     "oct 7, 1970",
84//!     "oct 7, 70",
85//!     "oct. 7, 1970",
86//!     "oct. 7, 70",
87//!     "October 7, 1970",
88//!     // dd Mon yyyy hh:mm:ss
89//!     "12 Feb 2006, 19:17",
90//!     "12 Feb 2006 19:17",
91//!     "14 May 2019 19:11:40.164",
92//!     // dd Mon yyyy
93//!     "7 oct 70",
94//!     "7 oct 1970",
95//!     "03 February 2013",
96//!     "1 July 2013",
97//!     // mm/dd/yyyy hh:mm:ss
98//!     "4/8/2014 22:05",
99//!     "04/08/2014 22:05",
100//!     "4/8/14 22:05",
101//!     "04/2/2014 03:00:51",
102//!     "8/8/1965 12:00:00 AM",
103//!     "8/8/1965 01:00:01 PM",
104//!     "8/8/1965 01:00 PM",
105//!     "8/8/1965 1:00 PM",
106//!     "8/8/1965 12:00 AM",
107//!     "4/02/2014 03:00:51",
108//!     "03/19/2012 10:11:59",
109//!     "03/19/2012 10:11:59.3186369",
110//!     "03/19/2012 10:11:59.318 PM",
111//!     // mm/dd/yyyy
112//!     "3/31/2014",
113//!     "03/31/2014",
114//!     "08/21/71",
115//!     "8/1/71",
116//!     // yyyy/mm/dd hh:mm:ss
117//!     "2014/4/8 22:05",
118//!     "2014/04/08 22:05",
119//!     "2014/04/2 03:00:51",
120//!     "2014/4/02 03:00:51",
121//!     "2012/03/19 10:11:59",
122//!     "2012/03/19 10:11:59.3186369",
123//!     "2012/03/19 10:11:59.318 PM",
124//!     // yyyy/mm/dd
125//!     "2014/3/31",
126//!     "2014/03/31",
127//! ];
128//!
129//! for date_str in accepted {
130//!     let result = date_str.parse::<DateTimeUtc>();
131//!     assert!(result.is_ok())
132//! }
133//! ```
134//!
135//! ### DMY Format
136//!
137//! It also accepts dates in DMY format with `parse_with_preference`,
138//! and the `prefer_dmy` parameter set to true.
139//!
140//! ```
141//! use qsv_dateparser::parse_with_preference;
142//!
143//! let accepted = vec![
144//!     // dd/mm/yyyy
145//!     "31/12/2020",
146//!     "12/10/2019",
147//!     "03/06/2018",
148//!     "27/06/68",
149//!     // dd/mm/yyyy hh:mm:ss
150//!     "4/8/2014 22:05",
151//!     "04/08/2014 22:05",
152//!     "4/8/14 22:05",
153//!     "04/2/2014 03:00:51",
154//!     "8/8/1965 12:00:00 AM",
155//!     "8/8/1965 01:00:01 PM",
156//!     "8/8/1965 01:00 PM",
157//!     "31/12/22 15:00",
158//!     "19/03/2012 10:11:59.318 PM"
159//! ];
160//!
161//! for date_str in accepted {
162//!     let result = parse_with_preference(date_str, true);
163//!     assert!(result.is_ok());
164//! }
165//! ```
166
167/// Datetime string parser
168///
169/// ```
170/// use chrono::prelude::*;
171/// use qsv_dateparser::datetime::Parse;
172/// use std::error::Error;
173///
174/// fn main() -> Result<(), Box<dyn Error>> {
175///     let utc_now_time = Utc::now().time();
176///     let parse_with_local = Parse::new(&Local, utc_now_time);
177///     assert_eq!(
178///         parse_with_local.parse("2021-06-05 06:19 PM")?,
179///         Local.ymd(2021, 6, 5).and_hms(18, 19, 0).with_timezone(&Utc),
180///     );
181///
182///     let parse_with_utc = Parse::new(&Utc, utc_now_time);
183///     assert_eq!(
184///         parse_with_utc.parse("2021-06-05 06:19 PM")?,
185///         Utc.ymd(2021, 6, 5).and_hms(18, 19, 0),
186///     );
187///
188///     Ok(())
189/// }
190/// ```
191pub mod datetime;
192
193/// Timezone offset string parser
194///
195/// ```
196/// use chrono::prelude::*;
197/// use qsv_dateparser::timezone::parse;
198/// use std::error::Error;
199///
200/// fn main() -> Result<(), Box<dyn Error>> {
201///     assert_eq!(parse("-0800")?, FixedOffset::west(8 * 3600));
202///     assert_eq!(parse("+10:00")?, FixedOffset::east(10 * 3600));
203///     assert_eq!(parse("PST")?, FixedOffset::west(8 * 3600));
204///     assert_eq!(parse("PDT")?, FixedOffset::west(7 * 3600));
205///     assert_eq!(parse("UTC")?, FixedOffset::west(0));
206///     assert_eq!(parse("GMT")?, FixedOffset::west(0));
207///
208///     Ok(())
209/// }
210/// ```
211pub mod timezone;
212
213use crate::datetime::Parse;
214use anyhow::{Error, Result};
215use chrono::prelude::*;
216
217/// `DateTimeUtc` is an alias for `chrono`'s `DateTime<UTC>`. It implements `std::str::FromStr`'s
218/// `from_str` method, and it makes `str`'s `parse` method to understand the accepted date formats
219/// from this crate.
220///
221/// ```
222/// use qsv_dateparser::DateTimeUtc;
223///
224/// // parsed is DateTimeUTC and parsed.0 is chrono's DateTime<Utc>
225/// match "May 02, 2021 15:51:31 UTC".parse::<DateTimeUtc>() {
226///     Ok(parsed) => println!("PARSED into UTC datetime {:?}", parsed.0),
227///     Err(err) => println!("ERROR from parsing datetime string: {}", err)
228/// }
229/// ```
230pub struct DateTimeUtc(pub DateTime<Utc>);
231
232impl std::str::FromStr for DateTimeUtc {
233    type Err = Error;
234
235    fn from_str(s: &str) -> Result<Self> {
236        parse(s).map(DateTimeUtc)
237    }
238}
239
240const MIDNIGHT: NaiveTime = NaiveTime::MIN;
241
242/// This function tries to recognize the input datetime string with a list of accepted formats.
243/// When timezone is not provided, this function assumes it's a [`chrono::Local`] datetime. For
244/// custom timezone, use [`parse_with_timezone()`] instead.If all options are exhausted,
245/// [`parse()`] will return an error to let the caller know that no formats were matched.
246///
247/// A date-only input (no time of day, e.g. `2021-02-21`) is the written date at the current
248/// UTC time: its UTC date is always the written date, and the timezone is not applied to it.
249#[inline]
250pub fn parse(input: &str) -> Result<DateTime<Utc>> {
251    Parse::new(&Local, Utc::now().time()).parse(input)
252}
253
254/// Similar to [`parse()`], this function takes a datetime string and a boolean `dmy_preference`.
255/// When `dmy_preference` is `true`, it will parse strings using the DMY format. Otherwise, it
256/// parses them using an MDY format.
257#[inline]
258pub fn parse_with_preference(input: &str, dmy_preference: bool) -> Result<DateTime<Utc>> {
259    Parse::new_with_preference(&Utc, MIDNIGHT, dmy_preference).parse(input)
260}
261
262/// Similar to [`parse()`], this function takes a datetime string and a custom [`chrono::TimeZone`],
263/// and tries to parse the datetime string. When timezone is not given in the string, this function
264/// will assume and parse the datetime by the custom timezone provided in this function's arguments.
265///
266/// A date-only input (no time of day) is the written date at the current UTC time; `tz` and
267/// any offset in the input apply only to inputs with a time of day.
268#[inline]
269pub fn parse_with_timezone<Tz2: TimeZone>(input: &str, tz: &Tz2) -> Result<DateTime<Utc>> {
270    Parse::new(tz, Utc::now().time()).parse(input)
271}
272
273/// Similar to [`parse()`], this function takes a datetime string and a boolean `dmy_preference`
274/// and a timezone. When timezone is not given in the input string, this function will
275/// assume and parse the datetime by the custom timezone provided in this function's arguments.
276/// When `dmy_preference` is `true`, it will parse strings using the DMY format. Otherwise, it
277/// parses them using an MDY format.
278///
279/// A date-only input (no time of day) is midnight UTC on the written date; `tz` and any offset
280/// in the input apply only to inputs with a time of day.
281#[inline]
282pub fn parse_with_preference_and_timezone<Tz2: TimeZone>(
283    input: &str,
284    dmy_preference: bool,
285    tz: &Tz2,
286) -> Result<DateTime<Utc>> {
287    Parse::new_with_preference(tz, MIDNIGHT, dmy_preference).parse(input)
288}
289
290/// Similar to [`parse()`] and [`parse_with_timezone()`], this function takes a datetime string, a
291/// custom [`chrono::TimeZone`] and a default naive time. In addition to assuming timezone when
292/// it's not given in datetime string, this function also use provided default naive time in parsed
293/// [`chrono::DateTime`].
294///
295/// `default_time` is a UTC time: a date-only input (no time of day) is the written date at
296/// `default_time` in UTC, and `tz` and any offset in the input apply only to inputs with a
297/// time of day.
298#[inline]
299pub fn parse_with<Tz2: TimeZone>(
300    input: &str,
301    tz: &Tz2,
302    default_time: NaiveTime,
303) -> Result<DateTime<Utc>> {
304    Parse::new(tz, default_time).parse(input)
305}
306
307#[cfg(test)]
308#[allow(deprecated)]
309mod tests {
310    use super::*;
311
312    /// Every date string quoted in the README's "Accepted date formats" list
313    /// must actually parse.
314    ///
315    /// The equivalent list in this file's crate docs is a doctest, so CI
316    /// catches it when an entry stops parsing. The README's copy had no such
317    /// check, which is why it was the one that drifted. Reading it back from
318    /// `include_str!` gives it the same guarantee.
319    ///
320    /// Note this catches a README that *claims* a format the crate does not
321    /// accept; it cannot catch a newly accepted format the README omits.
322    #[test]
323    fn readme_accepted_formats_all_parse() {
324        let readme = include_str!("../README.md");
325
326        // Narrow to the fenced block under the heading. Scanning the whole
327        // file would pick up any future quoted line elsewhere in the README
328        // and fail on it even though it was never meant to be a date.
329        let after_heading = readme
330            .split_once("## Accepted date formats")
331            .expect("README lost its '## Accepted date formats' heading")
332            .1;
333        let after_fence_marker = after_heading
334            .split_once("```")
335            .expect("the accepted-formats section lost its opening code fence")
336            .1;
337        // Drop the remainder of the fence line, which carries the language tag.
338        let block_start = after_fence_marker
339            .split_once('\n')
340            .expect("the opening code fence is not terminated")
341            .1;
342        let block = block_start
343            .split_once("```")
344            .expect("the accepted-formats section lost its closing code fence")
345            .0;
346
347        // Every line in the block must be recognised as a comment or a quoted
348        // entry. A bare count would let a reformat silently drop entries while
349        // the test still passed; refusing to skip anything is what makes this
350        // a completeness check rather than a sample.
351        let mut checked = 0_usize;
352        for line in block.lines() {
353            let line = line.trim();
354            if line.is_empty() || line.starts_with("//") {
355                continue;
356            }
357            let input = line
358                .strip_suffix(',')
359                .unwrap_or(line)
360                .strip_prefix('"')
361                .and_then(|rest| rest.strip_suffix('"'))
362                .unwrap_or_else(|| {
363                    panic!("unparsable line in the accepted-formats block: {line:?}")
364                });
365            // The list mixes MDY- and DMY-ordered examples, so accept either
366            // preference — the README documents both under one heading.
367            assert!(
368                parse_with_preference(input, false).is_ok()
369                    || parse_with_preference(input, true).is_ok(),
370                "README lists {input:?}, but it does not parse"
371            );
372            checked += 1;
373        }
374        // Backstop against the block being emptied or truncated entirely,
375        // which the per-line check above cannot see.
376        assert!(
377            checked >= 80,
378            "expected the full accepted-formats list, only found {checked} entries"
379        );
380    }
381
382    #[derive(Clone, Copy)]
383    enum Trunc {
384        Seconds,
385        None,
386    }
387
388    #[test]
389    fn parse_in_local() {
390        let test_cases = vec![
391            (
392                "rfc3339",
393                "2017-11-25T22:34:50Z",
394                Utc.ymd(2017, 11, 25).and_hms(22, 34, 50),
395                Trunc::None,
396            ),
397            (
398                "rfc2822",
399                "Wed, 02 Jun 2021 06:31:39 GMT",
400                Utc.ymd(2021, 6, 2).and_hms(6, 31, 39),
401                Trunc::None,
402            ),
403            (
404                "ymd_hms",
405                "2021-04-30 21:14:10",
406                Local
407                    .ymd(2021, 4, 30)
408                    .and_hms(21, 14, 10)
409                    .with_timezone(&Utc),
410                Trunc::None,
411            ),
412            (
413                "ymd_hms_z",
414                "2017-11-25 13:31:15 PST",
415                Utc.ymd(2017, 11, 25).and_hms(21, 31, 15),
416                Trunc::None,
417            ),
418            (
419                "ymd",
420                "2021-02-21",
421                Utc.ymd(2021, 2, 21).and_time(Utc::now().time()).unwrap(),
422                Trunc::Seconds,
423            ),
424            (
425                "ymd_z",
426                "2021-02-21 PST",
427                Utc.ymd(2021, 2, 21).and_time(Utc::now().time()).unwrap(),
428                Trunc::Seconds,
429            ),
430            (
431                "month_ymd",
432                "2021-Feb-21",
433                Utc.ymd(2021, 2, 21).and_time(Utc::now().time()).unwrap(),
434                Trunc::Seconds,
435            ),
436            (
437                "month_mdy_hms",
438                "May 8, 2009 5:57:51 PM",
439                Local
440                    .ymd(2009, 5, 8)
441                    .and_hms(17, 57, 51)
442                    .with_timezone(&Utc),
443                Trunc::None,
444            ),
445            (
446                "month_mdy_hms_z",
447                "May 02, 2021 15:51 UTC",
448                Utc.ymd(2021, 5, 2).and_hms(15, 51, 0),
449                Trunc::None,
450            ),
451            (
452                "month_mdy",
453                "May 25, 2021",
454                Utc.ymd(2021, 5, 25).and_time(Utc::now().time()).unwrap(),
455                Trunc::Seconds,
456            ),
457            (
458                "month_dmy_hms",
459                "14 May 2019 19:11:40.164",
460                Local
461                    .ymd(2019, 5, 14)
462                    .and_hms_milli(19, 11, 40, 164)
463                    .with_timezone(&Utc),
464                Trunc::None,
465            ),
466            (
467                "month_dmy",
468                "1 July 2013",
469                Utc.ymd(2013, 7, 1).and_time(Utc::now().time()).unwrap(),
470                Trunc::Seconds,
471            ),
472            (
473                "slash_mdy_hms",
474                "03/19/2012 10:11:59",
475                Local
476                    .ymd(2012, 3, 19)
477                    .and_hms(10, 11, 59)
478                    .with_timezone(&Utc),
479                Trunc::None,
480            ),
481            (
482                "slash_mdy",
483                "08/21/71",
484                Utc.ymd(1971, 8, 21).and_time(Utc::now().time()).unwrap(),
485                Trunc::Seconds,
486            ),
487            (
488                "slash_ymd_hms",
489                "2012/03/19 10:11:59",
490                Local
491                    .ymd(2012, 3, 19)
492                    .and_hms(10, 11, 59)
493                    .with_timezone(&Utc),
494                Trunc::None,
495            ),
496            (
497                "slash_ymd",
498                "2014/3/31",
499                Utc.ymd(2014, 3, 31).and_time(Utc::now().time()).unwrap(),
500                Trunc::Seconds,
501            ),
502        ];
503
504        for &(test, input, want, trunc) in test_cases.iter() {
505            match trunc {
506                Trunc::None => {
507                    assert_eq!(
508                        super::parse(input).unwrap(),
509                        want,
510                        "parse_in_local/{}/{}",
511                        test,
512                        input
513                    )
514                }
515                Trunc::Seconds => assert_eq!(
516                    super::parse(input)
517                        .unwrap()
518                        .trunc_subsecs(0)
519                        .with_second(0)
520                        .unwrap(),
521                    want.trunc_subsecs(0).with_second(0).unwrap(),
522                    "parse_in_local/{}/{}",
523                    test,
524                    input
525                ),
526            };
527        }
528    }
529
530    #[test]
531    fn parse_with_timezone_in_utc() {
532        let test_cases = vec![
533            (
534                "rfc3339",
535                "2017-11-25T22:34:50Z",
536                Utc.ymd(2017, 11, 25).and_hms(22, 34, 50),
537                Trunc::None,
538            ),
539            (
540                "rfc2822",
541                "Wed, 02 Jun 2021 06:31:39 GMT",
542                Utc.ymd(2021, 6, 2).and_hms(6, 31, 39),
543                Trunc::None,
544            ),
545            (
546                "ymd_hms",
547                "2021-04-30 21:14:10",
548                Utc.ymd(2021, 4, 30).and_hms(21, 14, 10),
549                Trunc::None,
550            ),
551            (
552                "ymd_hms_z",
553                "2017-11-25 13:31:15 PST",
554                Utc.ymd(2017, 11, 25).and_hms(21, 31, 15),
555                Trunc::None,
556            ),
557            (
558                "ymd",
559                "2021-02-21",
560                Utc.ymd(2021, 2, 21).and_time(Utc::now().time()).unwrap(),
561                Trunc::Seconds,
562            ),
563            (
564                "ymd_z",
565                "2021-02-21 PST",
566                Utc.ymd(2021, 2, 21).and_time(Utc::now().time()).unwrap(),
567                Trunc::Seconds,
568            ),
569            (
570                "month_ymd",
571                "2021-Feb-21",
572                Utc.ymd(2021, 2, 21).and_time(Utc::now().time()).unwrap(),
573                Trunc::Seconds,
574            ),
575            (
576                "month_mdy_hms",
577                "May 8, 2009 5:57:51 PM",
578                Utc.ymd(2009, 5, 8).and_hms(17, 57, 51),
579                Trunc::None,
580            ),
581            (
582                "month_mdy_hms_z",
583                "May 02, 2021 15:51 UTC",
584                Utc.ymd(2021, 5, 2).and_hms(15, 51, 0),
585                Trunc::None,
586            ),
587            (
588                "month_mdy",
589                "May 25, 2021",
590                Utc.ymd(2021, 5, 25).and_time(Utc::now().time()).unwrap(),
591                Trunc::Seconds,
592            ),
593            (
594                "month_dmy_hms",
595                "14 May 2019 19:11:40.164",
596                Utc.ymd(2019, 5, 14).and_hms_milli(19, 11, 40, 164),
597                Trunc::None,
598            ),
599            (
600                "month_dmy",
601                "1 July 2013",
602                Utc.ymd(2013, 7, 1).and_time(Utc::now().time()).unwrap(),
603                Trunc::Seconds,
604            ),
605            (
606                "slash_mdy_hms",
607                "03/19/2012 10:11:59",
608                Utc.ymd(2012, 3, 19).and_hms(10, 11, 59),
609                Trunc::None,
610            ),
611            (
612                "slash_mdy",
613                "08/21/71",
614                Utc.ymd(1971, 8, 21).and_time(Utc::now().time()).unwrap(),
615                Trunc::Seconds,
616            ),
617            (
618                "slash_ymd_hms",
619                "2012/03/19 10:11:59",
620                Utc.ymd(2012, 3, 19).and_hms(10, 11, 59),
621                Trunc::None,
622            ),
623            (
624                "slash_ymd",
625                "2014/3/31",
626                Utc.ymd(2014, 3, 31).and_time(Utc::now().time()).unwrap(),
627                Trunc::Seconds,
628            ),
629        ];
630
631        for &(test, input, want, trunc) in test_cases.iter() {
632            match trunc {
633                Trunc::None => {
634                    assert_eq!(
635                        super::parse_with_timezone(input, &Utc).unwrap(),
636                        want,
637                        "parse_with_timezone_in_utc/{}/{}",
638                        test,
639                        input
640                    )
641                }
642                Trunc::Seconds => assert_eq!(
643                    super::parse_with_timezone(input, &Utc)
644                        .unwrap()
645                        .trunc_subsecs(0)
646                        .with_second(0)
647                        .unwrap(),
648                    want.trunc_subsecs(0).with_second(0).unwrap(),
649                    "parse_with_timezone_in_utc/{}/{}",
650                    test,
651                    input
652                ),
653            };
654        }
655    }
656
657    #[test]
658    fn parse_with_preference_and_timezone_in_utc() {
659        let current_time = Utc::now().time();
660        let current_hour = current_time.hour();
661        let current_minute = current_time.minute();
662        // let current_second = current_time.second();
663        let test_cases = vec![
664            (
665                "rfc3339",
666                "2017-11-25T22:34:50Z",
667                Utc.ymd(2017, 11, 25).and_hms(22, 34, 50),
668                Trunc::None,
669            ),
670            (
671                "rfc2822",
672                "Wed, 02 Jun 2021 06:31:39 GMT",
673                Utc.ymd(2021, 6, 2).and_hms(6, 31, 39),
674                Trunc::None,
675            ),
676            // we currently do not parse dmy format using hyphens,
677            // so the following tests are commented out
678            // (
679            //     "dmy_hms",
680            //     "30-04-2021 21:14:10",
681            //     Utc.ymd(2021, 4, 30).and_hms(21, 14, 10),
682            //     Trunc::None,
683            // ),
684            // (
685            //     "dmy_hms_z",
686            //     "25-11-2017 13:31:15 PST",
687            //     Utc.ymd(2017, 11, 25).and_hms(21, 31, 15),
688            //     Trunc::None,
689            // ),
690            // (
691            //     "dmy",
692            //     "21-02-2021",
693            //     // Utc.ymd(2021, 2, 21).and_time(Utc::now().time()).unwrap(),
694            //     Utc.with_ymd_and_hms(2021, 2, 21, current_hour, current_minute, current_second)
695            //         .unwrap(),
696            //     Trunc::Seconds,
697            // ),
698            // (
699            //     "dmy_z",
700            //     "21-02-2021 PST",
701            //     FixedOffset::west(8 * 3600)
702            //         .ymd(2021, 2, 21)
703            //         .and_time(
704            //             Utc::now()
705            //                 .with_timezone(&FixedOffset::west(8 * 3600))
706            //                 .time(),
707            //         )
708            //         .unwrap()
709            //         .with_timezone(&Utc),
710            //     Trunc::Seconds,
711            // ),
712            // (
713            //     "month_dmy",
714            //     "21-Feb-2021",
715            //     Utc.ymd(2021, 2, 21).and_time(Utc::now().time()).unwrap(),
716            //     Trunc::Seconds,
717            // ),
718            (
719                "month_mdy_hms",
720                "May 8, 2009 5:57:51 PM",
721                Utc.ymd(2009, 5, 8).and_hms(17, 57, 51),
722                Trunc::None,
723            ),
724            (
725                "month_mdy_hms_z",
726                "May 02, 2021 15:51 UTC",
727                Utc.ymd(2021, 5, 2).and_hms(15, 51, 0),
728                Trunc::None,
729            ),
730            (
731                "month_mdy",
732                "May 25, 2021",
733                Utc.ymd(2021, 5, 25).and_time(Utc::now().time()).unwrap(),
734                Trunc::Seconds,
735            ),
736            (
737                "month_dmy_hms",
738                "14 May 2019 19:11:40.164",
739                Utc.ymd(2019, 5, 14).and_hms_milli(19, 11, 40, 164),
740                Trunc::None,
741            ),
742            (
743                "month_dmy",
744                "1 July 2013",
745                Utc.ymd(2013, 7, 1).and_time(Utc::now().time()).unwrap(),
746                Trunc::Seconds,
747            ),
748            (
749                "slash_dmy_hms",
750                "19/03/2012 10:11:59",
751                Utc.ymd(2012, 3, 19).and_hms(10, 11, 59),
752                Trunc::None,
753            ),
754            (
755                "slash_dmy",
756                "21/08/71",
757                Utc.ymd(1971, 8, 21).and_time(Utc::now().time()).unwrap(),
758                Trunc::Seconds,
759            ),
760            (
761                "slash_dmy_hms",
762                "19/03/2012 10:11:59",
763                Utc.ymd(2012, 3, 19).and_hms(10, 11, 59),
764                Trunc::None,
765            ),
766            (
767                "slash_dmy",
768                "31/3/2014",
769                Utc.ymd(2014, 3, 31).and_time(Utc::now().time()).unwrap(),
770                Trunc::Seconds,
771            ),
772        ];
773
774        for &(test, input, want, trunc) in test_cases.iter() {
775            match trunc {
776                Trunc::None => {
777                    assert_eq!(
778                        super::parse_with_preference_and_timezone(input, true, &Utc).unwrap(),
779                        want,
780                        "parse_with_preference_and_timezone_in_utc/{}/{}",
781                        test,
782                        input
783                    )
784                }
785                Trunc::Seconds => assert_eq!(
786                    super::parse_with_preference_and_timezone(input, true, &Utc)
787                        .unwrap()
788                        .trunc_subsecs(0)
789                        .with_hour(current_hour)
790                        .unwrap()
791                        .with_minute(current_minute)
792                        .unwrap()
793                        .with_second(0)
794                        .unwrap(),
795                    want.trunc_subsecs(0).with_second(0).unwrap(),
796                    "parse_with_preference_and_timezone_in_utc/{}/{}",
797                    test,
798                    input
799                ),
800            };
801        }
802    }
803
804    #[test]
805    fn parse_unambiguous_dmy() {
806        // A date-only input keeps its written date as the UTC date, whatever the
807        // host TZ or the moment the test runs.
808        assert_eq!(
809            super::parse("31/3/22").unwrap().date(),
810            Utc.ymd(2022, 3, 31)
811        );
812        assert_eq!(
813            super::parse_with_preference("3/31/22", true)
814                .unwrap()
815                .date(),
816            Utc.ymd(2022, 3, 31)
817        );
818        assert_eq!(
819            super::parse_with_preference("31/07/2021", true)
820                .unwrap()
821                .date(),
822            Utc.ymd(2021, 7, 31)
823        );
824    }
825
826    // Regression: ISO 8601 with 'T' separator and no timezone (e.g. Python's
827    // datetime.isoformat() without astimezone) must parse via the naive
828    // wall-clock path, matching the equivalent space-separated form.
829    #[test]
830    fn parse_iso_t_no_tz() {
831        // Bare T, no fractional, no tz.
832        let got = super::parse_with_preference("2020-01-15T08:00:00", false).unwrap();
833        assert_eq!(got, Utc.ymd(2020, 1, 15).and_hms(8, 0, 0));
834
835        // T, no seconds, no tz.
836        let got = super::parse_with_preference("2020-01-15T08:00", false).unwrap();
837        assert_eq!(got, Utc.ymd(2020, 1, 15).and_hms(8, 0, 0));
838
839        // T with millisecond + microsecond + nanosecond precision.
840        for (input, want) in [
841            (
842                "2020-01-15T08:00:00.123",
843                Utc.ymd(2020, 1, 15).and_hms_milli(8, 0, 0, 123),
844            ),
845            (
846                "2020-01-15T08:00:00.123456",
847                Utc.ymd(2020, 1, 15).and_hms_micro(8, 0, 0, 123456),
848            ),
849            (
850                "2020-01-15T08:00:00.123456789",
851                Utc.ymd(2020, 1, 15).and_hms_nano(8, 0, 0, 123456789),
852            ),
853        ] {
854            assert_eq!(
855                super::parse_with_preference(input, false).unwrap(),
856                want,
857                "parse_iso_t_no_tz/{input}"
858            );
859        }
860
861        // T-form and space-form must produce the same instant.
862        assert_eq!(
863            super::parse_with_preference("2020-01-15T08:00:00", false).unwrap(),
864            super::parse_with_preference("2020-01-15 08:00:00", false).unwrap(),
865        );
866
867        // Existing tz-bearing T-forms must continue to parse (no regression).
868        assert!(super::parse_with_preference("2020-01-15T08:00:00Z", false).is_ok());
869        assert!(super::parse_with_preference("2020-01-15T08:00:00+00:00", false).is_ok());
870    }
871
872    // Structural pre-filter: inputs containing a byte that cannot appear in any
873    // accepted date format (e.g. '_', '#', non-ASCII) must fail fast, while every
874    // currently-accepted input must still parse. Correctness guard for the
875    // pre-filter optimization (must not change which strings parse).
876    #[test]
877    fn prefilter_rejects_non_date_strings() {
878        // The qsv-dateparser-opt failure hot path: '_' is not a valid date byte.
879        for input in [
880            "category_value_123",
881            "first_name",
882            "value#42",
883            "a(b)c1",
884            "100%",
885            "naïve_2020", // non-ASCII byte
886        ] {
887            assert!(
888                super::parse(input).is_err(),
889                "prefilter should reject {input}"
890            );
891        }
892
893        // Pre-filter must NOT reject anything that currently parses. Spot-check
894        // every separator family.
895        for input in [
896            "2021-04-30 21:14:10",           // '-' ':' space
897            "2020-07-20+08:00",              // '+'
898            "03/19/2012 10:11:59.3186369",   // '/' '.'
899            "May 26, 2021, 12:49 AM PDT",    // ',' letters
900            "Wed, 02 Jun 2021 06:31:39 GMT", // rfc2822
901            "1671673426.123456789",          // timestamp with '.'
902            "-770172300",                    // negative timestamp
903        ] {
904            assert!(
905                super::parse(input).is_ok(),
906                "prefilter must not reject {input}"
907            );
908        }
909    }
910}