parse_datetime 0.14.0

parsing human-readable time strings and converting them to a DateTime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//! A Rust crate for parsing human-readable relative time strings and human-readable datetime strings and converting them to a `DateTime`.
//! The function supports the following formats for time:
//!
//! * ISO formats
//! * timezone offsets, e.g., "UTC-0100"
//! * unix timestamps, e.g., "@12"
//! * relative time to now, e.g. "+1 hour"
//!
use std::error::Error;
use std::fmt::{self, Display};

use jiff::Zoned;

mod items;

#[derive(Debug, PartialEq)]
pub enum ParseDateTimeError {
    InvalidInput,
}

impl Display for ParseDateTimeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParseDateTimeError::InvalidInput => {
                write!(
                    f,
                    "Invalid input string: cannot be parsed as a relative time"
                )
            }
        }
    }
}

impl Error for ParseDateTimeError {}

impl From<items::error::Error> for ParseDateTimeError {
    fn from(_: items::error::Error) -> Self {
        ParseDateTimeError::InvalidInput
    }
}

/// Parses a time string and returns a `Zoned` object representing the absolute
/// time of the string.
///
/// # Arguments
///
/// * `input` - A string slice representing the time.
///
/// # Examples
///
/// ```
/// use jiff::Zoned;
/// use parse_datetime::parse_datetime;
///
/// let time = parse_datetime("2023-06-03 12:00:01Z").unwrap();
/// assert_eq!(time.strftime("%F %T").to_string(), "2023-06-03 12:00:01");
/// ```
///
///
/// # Returns
///
/// * `Ok(Zoned)` - If the input string can be parsed as a time
/// * `Err(ParseDateTimeError)` - If the input string cannot be parsed as a
///   relative time
///
/// # Errors
///
/// This function will return `Err(ParseDateTimeError::InvalidInput)` if the
/// input string cannot be parsed as a relative time.
pub fn parse_datetime<S: AsRef<str> + Clone>(input: S) -> Result<Zoned, ParseDateTimeError> {
    items::parse_at_local(input).map_err(|e| e.into())
}

/// Parses a time string at a specific date and returns a `Zoned` object
/// representing the absolute time of the string.
///
/// # Arguments
///
/// * date - The date represented in local time
/// * `input` - A string slice representing the time.
///
/// # Examples
///
/// ```
/// use jiff::Zoned;
/// use parse_datetime::parse_datetime_at_date;
///
///  let now = Zoned::now();
///  let after = parse_datetime_at_date(now, "2024-09-13UTC +3 days").unwrap();
///
///  assert_eq!(
///    "2024-09-16",
///    after.strftime("%F").to_string()
///  );
/// ```
///
/// # Returns
///
/// * `Ok(Zoned)` - If the input string can be parsed as a time
/// * `Err(ParseDateTimeError)` - If the input string cannot be parsed as a
///   relative time
///
/// # Errors
///
/// This function will return `Err(ParseDateTimeError::InvalidInput)` if the
/// input string cannot be parsed as a relative time.
pub fn parse_datetime_at_date<S: AsRef<str> + Clone>(
    date: Zoned,
    input: S,
) -> Result<Zoned, ParseDateTimeError> {
    items::parse_at_date(date, input).map_err(|e| e.into())
}

#[cfg(test)]
mod tests {
    use jiff::{
        civil::{date, time, Time, Weekday},
        ToSpan, Zoned,
    };

    use crate::parse_datetime;

    #[cfg(test)]
    mod iso_8601 {
        use crate::parse_datetime;

        static TEST_TIME: i64 = 1613371067;

        #[test]
        fn test_t_sep() {
            let dt = "2021-02-15T06:37:47 +0000";
            let actual = parse_datetime(dt).unwrap();
            assert_eq!(actual.timestamp().as_second(), TEST_TIME);
        }

        #[test]
        fn test_space_sep() {
            let dt = "2021-02-15 06:37:47 +0000";
            let actual = parse_datetime(dt).unwrap();
            assert_eq!(actual.timestamp().as_second(), TEST_TIME);
        }

        #[test]
        fn test_space_sep_offset() {
            let dt = "2021-02-14 22:37:47 -0800";
            let actual = parse_datetime(dt).unwrap();
            assert_eq!(actual.timestamp().as_second(), TEST_TIME);
        }

        #[test]
        fn test_t_sep_offset() {
            let dt = "2021-02-14T22:37:47 -0800";
            let actual = parse_datetime(dt).unwrap();
            assert_eq!(actual.timestamp().as_second(), TEST_TIME);
        }

        #[test]
        fn test_t_sep_single_digit_offset_no_space() {
            let dt = "2021-02-14T22:37:47-8";
            let actual = parse_datetime(dt).unwrap();
            assert_eq!(actual.timestamp().as_second(), TEST_TIME);
        }

        #[test]
        fn invalid_formats() {
            let invalid_dts = vec![
                "NotADate",
                "202104",
                "202104-12T22:37:47",
                "a774e26sec", // 774e26 is not a valid seconds value (we don't accept E-notation)
                "12.",        // Invalid floating point number
            ];
            for dt in invalid_dts {
                assert!(
                    parse_datetime(dt).is_err(),
                    "Expected error for input: {}",
                    dt
                );
            }
        }

        #[test]
        fn test_epoch_seconds() {
            let dt = "@1613371067";
            let actual = parse_datetime(dt).unwrap();
            assert_eq!(actual.timestamp().as_second(), TEST_TIME);
        }

        // #[test]
        // fn test_epoch_seconds_non_utc() {
        //     env::set_var("TZ", "EST");
        //     let dt = "@1613371067";
        //     let actual = parse_datetime(dt).unwrap();
        //     assert_eq!(actual.timestamp().as_second(), TEST_TIME);
        // }
    }

    #[cfg(test)]
    mod calendar_date_items {
        use jiff::{
            civil::{date, time},
            Zoned,
        };

        use crate::parse_datetime;

        #[test]
        fn single_digit_month_day() {
            let expected = Zoned::now()
                .with()
                .date(date(1987, 5, 7))
                .time(time(0, 0, 0, 0))
                .build()
                .unwrap();

            assert_eq!(expected, parse_datetime("1987-05-07").unwrap());
            assert_eq!(expected, parse_datetime("1987-5-07").unwrap());
            assert_eq!(expected, parse_datetime("1987-05-7").unwrap());
            assert_eq!(expected, parse_datetime("1987-5-7").unwrap());
            assert_eq!(expected, parse_datetime("5/7/1987").unwrap());
            assert_eq!(expected, parse_datetime("5/07/1987").unwrap());
            assert_eq!(expected, parse_datetime("05/7/1987").unwrap());
            assert_eq!(expected, parse_datetime("05/07/1987").unwrap());
        }
    }

    #[cfg(test)]
    mod offsets {
        use jiff::{civil::DateTime, tz, Zoned};

        use crate::parse_datetime;

        #[test]
        fn test_positive_offsets() {
            let offsets = vec![
                "UTC+07:00",
                "UTC+0700",
                "UTC+07",
                "Z+07:00",
                "Z+0700",
                "Z+07",
            ];

            let expected = format!("{}{}", Zoned::now().strftime("%Y%m%d"), "0000+0700");
            for offset in offsets {
                let actual = parse_datetime(offset).unwrap();
                assert_eq!(expected, actual.strftime("%Y%m%d%H%M%z").to_string());
            }
        }

        #[test]
        fn test_partial_offset() {
            let offsets = vec!["UTC+00:15", "UTC+0015", "Z+00:15", "Z+0015"];
            let expected = format!("{}{}", Zoned::now().strftime("%Y%m%d"), "0000+0015");
            for offset in offsets {
                let actual = parse_datetime(offset).unwrap();
                assert_eq!(expected, actual.strftime("%Y%m%d%H%M%z").to_string());
            }
        }

        #[test]
        fn test_datetime_with_offset() {
            let actual = parse_datetime("1997-01-19 08:17:48 +2").unwrap();
            let expected = "1997-01-19 08:17:48"
                .parse::<DateTime>()
                .unwrap()
                .to_zoned(tz::TimeZone::fixed(tz::offset(2)))
                .unwrap();
            assert_eq!(actual, expected);
        }

        #[test]
        fn test_datetime_with_timezone() {
            let actual = parse_datetime("1997-01-19 08:17:48 BRT").unwrap();
            let expected = "1997-01-19 08:17:48"
                .parse::<DateTime>()
                .unwrap()
                .to_zoned(tz::TimeZone::fixed(tz::offset(-3)))
                .unwrap();
            assert_eq!(actual, expected);
        }

        #[test]
        fn offset_overflow() {
            assert!(parse_datetime("m+25").is_err());
            assert!(parse_datetime("24:00").is_err());
        }
    }

    #[cfg(test)]
    mod relative_time {
        use crate::parse_datetime;

        #[test]
        fn test_positive_offsets() {
            let relative_times = vec![
                "today",
                "yesterday",
                "1 minute",
                "3 hours",
                "1 year 3 months",
            ];

            for relative_time in relative_times {
                assert!(parse_datetime(relative_time).is_ok());
            }
        }

        #[test]
        fn integer_seconds_offset() {
            let dt = "0 + 0 seconds";
            assert!(parse_datetime(dt).is_ok());
        }

        #[test]
        fn integer_seconds_offset_spaceless() {
            let dt = "0+0 seconds";
            assert!(parse_datetime(dt).is_ok());
        }

        #[test]
        fn floating_seconds_offset() {
            let dt = "0 + 0.0 seconds";
            assert!(parse_datetime(dt).is_ok());
        }

        #[test]
        fn floating_seconds_offset_spaceless() {
            let dt = "0+0.0 seconds";
            assert!(parse_datetime(dt).is_ok());
        }

        #[test]
        fn floating_seconds_offset_from_now() {
            let dt = "now  +  1.5 seconds";
            assert!(parse_datetime(dt).is_ok());
        }

        #[test]
        fn floating_seconds_offset_from_tomorrow_spaceless() {
            let dt = "tomorrow+1.5 seconds";
            assert!(parse_datetime(dt).is_ok());
        }
    }

    #[cfg(test)]
    mod weekday {
        use jiff::{civil::DateTime, tz::TimeZone, Zoned};

        use crate::parse_datetime_at_date;

        fn get_formatted_date(date: &Zoned, weekday: &str) -> String {
            let result = parse_datetime_at_date(date.clone(), weekday).unwrap();

            result.strftime("%F %T %9f").to_string()
        }

        #[test]
        fn test_weekday() {
            // add some constant hours and minutes and seconds to check its reset
            let date = "2023-02-28 10:12:03"
                .parse::<DateTime>()
                .unwrap()
                .to_zoned(TimeZone::system())
                .unwrap();

            // 2023-2-28 is tuesday
            assert_eq!(
                get_formatted_date(&date, "tuesday"),
                "2023-02-28 00:00:00 000000000"
            );

            // 2023-3-01 is wednesday
            assert_eq!(
                get_formatted_date(&date, "wed"),
                "2023-03-01 00:00:00 000000000"
            );

            assert_eq!(
                get_formatted_date(&date, "thu"),
                "2023-03-02 00:00:00 000000000"
            );

            assert_eq!(
                get_formatted_date(&date, "fri"),
                "2023-03-03 00:00:00 000000000"
            );

            assert_eq!(
                get_formatted_date(&date, "sat"),
                "2023-03-04 00:00:00 000000000"
            );

            assert_eq!(
                get_formatted_date(&date, "sun"),
                "2023-03-05 00:00:00 000000000"
            );
        }
    }

    #[cfg(test)]
    mod timestamp {
        use jiff::Timestamp;

        use crate::parse_datetime;

        #[test]
        fn test_positive_and_negative_offsets() {
            let offsets: Vec<i64> = vec![
                0, 1, 2, 10, 100, 150, 2000, 1234400000, 1334400000, 1692582913, 2092582910,
            ];

            for offset in offsets {
                // positive offset
                let time = Timestamp::from_second(offset).unwrap();
                let dt = parse_datetime(format!("@{offset}")).unwrap();
                assert_eq!(dt.timestamp(), time);

                // negative offset
                let time = Timestamp::from_second(-offset).unwrap();
                let dt = parse_datetime(format!("@-{offset}")).unwrap();
                assert_eq!(dt.timestamp(), time);
            }
        }
    }

    /// Used to test example code presented in the README.
    mod readme_test {
        use jiff::{civil::DateTime, tz::TimeZone};

        use crate::parse_datetime;

        #[test]
        fn test_readme_code() {
            let dt = parse_datetime("2021-02-14 06:37:47").unwrap();
            let expected = "2021-02-14 06:37:47"
                .parse::<DateTime>()
                .unwrap()
                .to_zoned(TimeZone::system())
                .unwrap();

            assert_eq!(dt, expected);
        }
    }

    mod invalid_test {
        use crate::parse_datetime;
        use crate::ParseDateTimeError;

        #[test]
        fn test_invalid_input() {
            let result = parse_datetime("foobar");
            assert_eq!(result, Err(ParseDateTimeError::InvalidInput));

            let result = parse_datetime("invalid 1");
            assert_eq!(result, Err(ParseDateTimeError::InvalidInput));
        }
    }

    #[test]
    fn test_datetime_ending_in_z() {
        let actual = parse_datetime("2023-06-03 12:00:01Z").unwrap();
        let expected = "2023-06-03 12:00:01[UTC]".parse::<Zoned>().unwrap();
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_parse_invalid_datetime() {
        assert!(crate::parse_datetime("bogus +1 day").is_err());
    }

    #[test]
    fn test_parse_invalid_delta() {
        assert!(crate::parse_datetime("1997-01-01 bogus").is_err());
    }

    #[test]
    fn test_parse_datetime_tz_nodelta() {
        // 1997-01-01 00:00:00 +0000
        let expected = "1997-01-01 00:00:00[UTC]".parse::<Zoned>().unwrap();

        for s in [
            "1997-01-01 00:00:00 +0000",
            "1997-01-01 00:00:00 +00",
            "1997-01-01 00:00 +0000",
            "1997-01-01 00:00:00 +0000",
            "1997-01-01T00:00:00+0000",
            "1997-01-01T00:00:00+00",
            "1997-01-01T00:00:00Z",
            "@852076800",
        ] {
            let actual = crate::parse_datetime(s).unwrap();
            assert_eq!(actual, expected);
        }
    }

    #[test]
    fn test_parse_datetime_notz_nodelta() {
        let expected = Zoned::now()
            .with()
            .date(date(1997, 1, 1))
            .time(time(0, 0, 0, 0))
            .build()
            .unwrap();

        for s in [
            "1997-01-01 00:00:00.000000000",
            "Wed Jan  1 00:00:00 1997",
            "1997-01-01T00:00:00",
            "1997-01-01 00:00:00",
            "1997-01-01 00:00",
        ] {
            let actual = crate::parse_datetime(s).unwrap();
            assert_eq!(actual, expected);
        }
    }

    #[test]
    fn test_parse_date_notz_nodelta() {
        let expected = Zoned::now()
            .with()
            .date(date(1997, 1, 1))
            .time(time(0, 0, 0, 0))
            .build()
            .unwrap();

        for s in ["1997-01-01", "19970101", "01/01/1997", "01/01/97"] {
            let actual = crate::parse_datetime(s).unwrap();
            assert_eq!(actual, expected);
        }
    }

    #[test]
    fn test_parse_datetime_tz_delta() {
        // 1998-01-01
        let expected = "1998-01-01 00:00:00[UTC]".parse::<Zoned>().unwrap();

        for s in [
            "1997-01-01 00:00:00 +0000 +1 year",
            "1997-01-01 00:00:00 +00 +1 year",
            "1997-01-01T00:00:00Z +1 year",
            "1997-01-01 00:00 +0000 +1 year",
            "1997-01-01 00:00:00 +0000 +1 year",
            "1997-01-01T00:00:00+0000 +1 year",
            "1997-01-01T00:00:00+00 +1 year",
        ] {
            let actual = crate::parse_datetime(s).unwrap();
            assert_eq!(actual, expected);
        }
    }

    #[test]
    fn test_parse_datetime_notz_delta() {
        let expected = Zoned::now()
            .with()
            .date(date(1998, 1, 1))
            .time(time(0, 0, 0, 0))
            .build()
            .unwrap();

        for s in [
            "1997-01-01 00:00:00.000000000 1 year",
            "Wed Jan  1 00:00:00 1997 1 year",
            "1997-01-01T00:00:00 1 year",
            "1997-01-01 00:00:00 1 year",
            "1997-01-01 00:00 1 year",
        ] {
            let actual = crate::parse_datetime(s).unwrap();
            assert_eq!(actual, expected);
        }
    }

    #[test]
    fn test_parse_invalid_datetime_notz_delta() {
        // GNU date does not accept the following formats.
        for s in ["199701010000.00 +1 year", "199701010000 +1 year"] {
            assert!(crate::parse_datetime(s).is_err());
        }
    }

    #[test]
    fn test_parse_date_notz_delta() {
        let expected = Zoned::now()
            .with()
            .date(date(1998, 1, 1))
            .time(time(0, 0, 0, 0))
            .build()
            .unwrap();

        for s in [
            "1997-01-01 +1 year",
            "19970101 +1 year",
            "01/01/1997 +1 year",
            "01/01/97 +1 year",
        ] {
            let actual = crate::parse_datetime(s).unwrap();
            assert_eq!(actual, expected);
        }
    }

    #[test]
    fn test_weekday_only() {
        let now = Zoned::now();
        let midnight = Time::new(0, 0, 0, 0).unwrap();
        let today = now.weekday();
        let midnight_today = now.with().time(midnight).build().unwrap();

        for (s, day) in [
            ("sunday", Weekday::Sunday),
            ("monday", Weekday::Monday),
            ("tuesday", Weekday::Tuesday),
            ("wednesday", Weekday::Wednesday),
            ("thursday", Weekday::Thursday),
            ("friday", Weekday::Friday),
            ("saturday", Weekday::Saturday),
        ] {
            let actual = parse_datetime(s).unwrap();
            let delta = day.since(today);
            let expected = midnight_today.checked_add(delta.days()).unwrap();
            assert_eq!(actual, expected);
        }
    }

    mod test_relative {
        use crate::parse_datetime;

        #[test]
        fn test_month() {
            assert_eq!(
                parse_datetime("28 feb + 1 month")
                    .expect("parse_datetime")
                    .strftime("%m%d")
                    .to_string(),
                "0328"
            );

            // 29 feb 2025 is invalid
            assert!(parse_datetime("29 feb + 1 year").is_err());

            // 29 feb 2025 is an invalid date
            assert!(parse_datetime("29 feb 2025").is_err());

            // because 29 feb 2025 is invalid, 29 feb 2025 + 1 day is invalid
            // arithmetic does not operate on invalid dates
            assert!(parse_datetime("29 feb 2025 + 1 day").is_err());

            // 28 feb 2023 + 1 day = 1 mar
            assert_eq!(
                parse_datetime("28 feb 2023 + 1 day")
                    .unwrap()
                    .strftime("%m%d")
                    .to_string(),
                "0301"
            );
        }

        #[test]
        fn month_overflow() {
            assert_eq!(
                parse_datetime("2024-01-31 + 1 month")
                    .unwrap()
                    .strftime("%Y-%m-%dT%H:%M:%S")
                    .to_string(),
                "2024-03-02T00:00:00",
            );

            assert_eq!(
                parse_datetime("2024-02-29 + 1 month")
                    .unwrap()
                    .strftime("%Y-%m-%dT%H:%M:%S")
                    .to_string(),
                "2024-03-29T00:00:00",
            );
        }
    }

    mod test_gnu {
        use crate::parse_datetime;

        #[test]
        fn gnu_compat() {
            const FMT: &str = "%Y-%m-%d %H:%M:%S";
            let input = "0000-03-02 00:00:00";
            assert_eq!(
                input,
                parse_datetime(input).unwrap().strftime(FMT).to_string()
            );

            let input = "2621-03-10 00:00:00";
            assert_eq!(
                input,
                parse_datetime(input).unwrap().strftime(FMT).to_string()
            );

            let input = "1038-03-10 00:00:00";
            assert_eq!(
                input,
                parse_datetime(input).unwrap().strftime(FMT).to_string()
            );
        }
    }
}