rtimelog 1.1.1

System for tracking time in a text-log-based format.
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//! Utilities for working with dates and times
//!
//! # Examples
//!
//! ```rust
//! use timelog::date::{Date, DateTime};
//! use timelog::Result;
//!
//! # fn main() -> Result<()> {
//! let mut day: Date = "2021-07-02".parse()?;
//! print!("Date: {}", day);
//!
//! let mut stamp: DateTime = "2021-07-02 12:34:00".parse()?;
//! print!("Stamp: {}", stamp);
//!
//! let mut today = Date::parse("today")?;
//! print!("Today: {}", today);
//! #   Ok(())
//! #  }
//! ```
//!
//! # Description
//!
//! The [`Date`] struct represents a date in the local time zone. The module also
//! provides tools for manipulating [`Date`]s.
//!
//! The [`DateRange`] struct represents a pair of dates in the local time zone.
//! The range represents a half-open range.
//!
//! The [`DateTime`] struct represents a date and time in the local time zone. The
//! module also provides tools for manipulating [`DateTime`]s.

use std::fmt::{self, Display};
use std::time::Duration;

use chrono::{Datelike, Local, NaiveDate, NaiveDateTime, NaiveTime, Timelike};

pub mod error;
pub mod parse;

/// Type shortcut for [`parse::DateParser`]
pub use parse::DateParser;
/// Type shortcut for [`parse::RangeParser`]
pub use parse::RangeParser;
/// Enum listing the days of the week. (From [`chrono::Weekday`])
pub type Weekday = chrono::Weekday;
/// Type for our internal time format.
pub type Time = chrono::NaiveTime;

/// Error type for errors in date functionality.
pub use error::DateError;
/// Result type for errors in date functionality.
pub type Result<T> = std::result::Result<T, DateError>;

/// Representation of a date in the local time zone.
#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq)]
pub struct Date(chrono::NaiveDate);

// Create Dates
impl Date {
    /// Create a [`Date`] out of a year, month, and day, returning a [`Result`].
    ///
    /// # Errors
    ///
    /// If one of the parameters is outside the legal range for a date, returns an
    /// [`DateError::InvalidDate`].
    pub fn new(year: i32, month: u32, day: u32) -> Result<Self> {
        Ok(Self(
            NaiveDate::from_ymd_opt(year, month, day).ok_or(DateError::InvalidDate)?
        ))
    }

    /// Create a [`Date`] for today.
    #[must_use]
    pub fn today() -> Self { Self(Local::now().date_naive()) }

    /// Create a [`Date`] object from the supplied date specification.
    ///
    /// Legal specifications include "today" and "yesterday", the days of the week "sunday"
    /// through "saturday", and a date in the form "YYYY-MM-DD".
    /// The days of the week result in the date representing the previous instance of that day
    /// (last Monday for "monday", etc.).
    ///
    /// # Errors
    ///
    /// Return [`DateError::InvalidDaySpec`] if the supplied spec is not valid.
    pub fn parse(datespec: &str) -> Result<Self> { DateParser::default().parse(datespec) }
}

// Accessors
impl Date {
    /// Return the year portion of the [`Date`]
    pub fn year(&self) -> i32 { self.0.year() }

    /// Return the month portion of the [`Date`]
    pub fn month(&self) -> u32 { self.0.month() }

    /// Return the day portion of the [`Date`]
    pub fn day(&self) -> u32 { self.0.day() }

    /// Return the day of the week enum.
    pub fn weekday(&self) -> Weekday { self.0.weekday() }

    /// Return the day of the week as a string.
    pub fn weekday_str(&self) -> &'static str {
        match self.0.weekday() {
            Weekday::Sun => "Sunday",
            Weekday::Mon => "Monday",
            Weekday::Tue => "Tuesday",
            Weekday::Wed => "Wednesday",
            Weekday::Thu => "Thursday",
            Weekday::Fri => "Friday",
            Weekday::Sat => "Saturday"
        }
    }
}

// Relative date methods
impl Date {
    /// Create a [`DateTime`] object for the first second of the current [`Date`]
    #[must_use]
    pub fn day_start(&self) -> DateTime {
        DateTime(self.0.and_hms_opt(0, 0, 0).expect("Midnight exists"))
    }

    /// Create a [`DateTime`] object for the last second of the current [`Date`]
    #[must_use]
    pub fn day_end(&self) -> DateTime {
        DateTime(self.0.and_hms_opt(23, 59, 59).expect("Midnight exists"))
    }

    // Find the last date before this one where the day of the week was
    // weekday.
    #[must_use]
    fn find_previous(&self, weekday: Weekday) -> Self {
        let mut day = self.0.pred_opt().expect("Not at beginning of time");
        while day.weekday() != weekday {
            day = day.pred_opt().expect("Not at beginning of time");
        }
        Self(day)
    }

    // Find the next date after this one where the day of the week was
    // weekday.
    #[must_use]
    fn find_next(&self, weekday: Weekday) -> Self {
        let mut day = self.0.succ_opt().expect("Not at end of time");
        while day.weekday() != weekday {
            day = day.succ_opt().expect("Not at end of time");
        }
        Self(day)
    }

    /// Create a [`Date`] object for the last day of the month.
    #[must_use]
    pub fn month_start(&self) -> Date { Date(self.0.with_day(1).expect("Reasonable date range")) }

    // Return true if the supplied year is a leap year
    fn is_leap_year(year: i32) -> bool {
        (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))
    }

    /// Create a [`Date`] object for the last day of the month.
    #[must_use]
    #[rustfmt::skip]
    pub fn month_end(&self) -> Date {
        let last_day = match self.0.month() {
            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
            4 | 6 | 9 | 11 => 30,
            2 => if Self::is_leap_year(self.0.year()) { 29 } else { 28 },
            _ => unreachable!()
        };
        Date(self.0.with_day(last_day).expect("End of month should work"))
    }

    /// Create a [`Date`] object for the first day of the week.
    #[must_use]
    pub fn week_start(&self) -> Date {
        match self.0.weekday() {
            Weekday::Sun => *self,
            _ => self.find_previous(Weekday::Sun)
        }
    }

    /// Create a [`Date`] object for the last day of the week.
    #[must_use]
    pub fn week_end(&self) -> Date {
        match self.0.weekday() {
            Weekday::Sat => *self,
            _ => self.find_next(Weekday::Sat)
        }
    }

    /// Create a [`Date`] object for the beginning of the year containing the date.
    #[must_use]
    pub fn year_start(&self) -> Date {
        Self(self.0
            .with_month(1).expect("Within reasonable dates")
            .with_day(1).expect("Within reasonable dates"))
    }

    /// Create a [`Date`] object for the end of the year containing the date.
    #[must_use]
    pub fn year_end(&self) -> Date {
        Self(self.0
            .with_month(12).expect("Within reasonable dates")
            .with_day(31).expect("Within reasonable dates"))
    }

    /// Create a [`Date`] for the day after the current date.
    #[must_use]
    pub fn succ(&self) -> Date { Self(self.0.succ_opt().expect("Not at end of time")) }

    /// Create a [`Date`] for the day before the current date.
    #[must_use]
    pub fn pred(&self) -> Date { Self(self.0.pred_opt().expect("Not at beginnning of time")) }
}

impl Default for Date {
    /// The default [`Date`] is the current day.
    fn default() -> Date { Self::today() }
}

impl std::str::FromStr for Date {
    type Err = DateError;

    /// Create a [`Date`] out of a string, returning a [`Result`]
    ///
    /// # Errors
    ///
    /// If the date is not formatted as 'YYYY-MM-DD', returns an [`DateError::InvalidDate`].
    /// Also if the date string cannot be converted into a [`Date`], returns an
    /// [`DateError::InvalidDate`].
    #[rustfmt::skip]
    fn from_str(date: &str) -> std::result::Result<Self, Self::Err> {
        let Ok(parsed) = NaiveDate::parse_from_str(date, "%Y-%m-%d") else {
            return Err(DateError::InvalidDate);
        };
        Ok(Self(parsed))
    }
}

impl Display for Date {
    /// Format a [`Date`] object in "YYYY-MM-DD" format.
    #[rustfmt::skip]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}-{:02}-{:02}", self.0.year(), self.0.month(), self.0.day())
    }
}

impl From<Date> for String {
    /// Convert a [`Date`] into a [`String`]
    fn from(date: Date) -> Self { date.to_string() }
}

/// Representation of a half-open range of dates in the local time zone.
#[derive(Debug, PartialEq, Eq)]
pub struct DateRange {
    start: Date,
    end:   Date
}

impl DateRange {
    /// Create [`DateRange`] with the supplied start and end dates. If
    /// The end is <= the start, create an empty [`DateRange`]
    pub fn new(start: Date, end: Date) -> Self {
        Self::new_opt(start, end).unwrap_or(Self { start, end: start })
    }

    /// Create [`DateRange`] if the start date is less than the end date.
    pub fn new_opt(start: Date, end: Date) -> Option<Self> {
        (start < end).then_some(Self { start, end })
    }

    /// Create [`DateRange`] from an iterator returning parts of a date range descriptor.
    ///
    /// # Errors
    ///
    /// - Return [`DateError::InvalidDate`] if the specification for a single day is not valid.
    /// - Return [`DateError::InvalidDaySpec`] if overall range specification is not valid.
    pub fn parse<'a, I>(datespec: &mut I) -> Result<Self>
    where
        I: Iterator<Item = &'a str>
    {
        RangeParser::default().parse(datespec).map(|(dr, _)| dr)
    }
}

impl DateRange {
    /// Return a copy of the start date for the range.
    pub fn start(&self) -> Date { self.start }

    /// Return a copy of the end date for the range.
    pub fn end(&self) -> Date { self.end }

    /// Return true if the range is empty.
    pub fn is_empty(&self) -> bool { self.start >= self.end }
}

impl From<Date> for DateRange {
    /// Create [`DateRange`] covering the supplied date.
    fn from(date: Date) -> DateRange { Self { start: date, end: date.succ() } }
}

impl Default for DateRange {
    /// The default [`DateRange`] covers just today.
    fn default() -> Self {
        let today = Date::today();
        Self { start: today, end: today.succ() }
    }
}

/// Representation of a date and time in the local time zone.
#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq)]
pub struct DateTime(chrono::NaiveDateTime);

impl DateTime {
    /// Create a [`DateTime`] from two tuples, one representing the date (year, month, day) and
    /// the second representing the time (hour, minute, second).
    ///
    /// # Errors
    ///
    /// Return an [`DateError::InvalidDate`] if the values in the tuples are not appropriate for the
    /// data types.
    pub fn new(date: (i32, u32, u32), time: (u32, u32, u32)) -> Result<Self> {
        let Some(d) = NaiveDate::from_ymd_opt(date.0, date.1, date.2) else {
            return Err(DateError::InvalidDate);
        };
        let Some(t) = NaiveTime::from_hms_opt(time.0, time.1, time.2) else {
            return Err(DateError::InvalidDate);
        };
        Ok(Self(NaiveDateTime::new(d, t)))
    }

    /// Create a [`Date`] for right now.
    pub fn now() -> Self { Self(Local::now().naive_local()) }

    // Create a new [`DateTime`] from a [`Date`] and a [`NaiveTime`]
    pub(crate) fn new_from_date_time(date: Date, time: NaiveTime) -> Self {
        Self(NaiveDateTime::new(date.0, time))
    }
}

impl DateTime {
    /// Return the epoch time representing the current value of the [`DateTime`] object.
    pub fn timestamp(&self) -> i64 { self.0.and_utc().timestamp() }

    /// Return a copy of just the [`Date`] portion of the [`DateTime`] object.
    pub fn date(&self) -> Date { Date(self.0.date()) }

    /// Return the hour of the day.
    pub fn hour(&self) -> u32 { self.0.hour() }

    /// Return the minute of the hour.
    pub fn minute(&self) -> u32 { self.0.minute() }

    /// Return the number of seconds after the hour.
    pub fn second_offset(&self) -> u32 { self.0.minute() * 60 + self.0.second() }

    /// Return the formatted time as a [`String`]
    pub fn hhmm(&self) -> String { format!("{:02}:{:02}", self.0.hour(), self.0.minute()) }
}

impl DateTime {
    /// Return a [`Duration`] lasting the supplied number of minutes.
    pub fn seconds(seconds: u64) -> Duration { Duration::from_secs(seconds) }

    /// Return a [`Duration`] lasting the supplied number of minutes.
    pub fn minutes(minutes: u64) -> Duration { Duration::from_secs(minutes * 60) }

    /// Return a [`Duration`] lasting the supplied number of hours.
    pub fn hours(hours: u64) -> Duration { Duration::from_secs(hours * 3600) }

    /// Return a [`Duration`] lasting the supplied number of days.
    pub fn days(days: u64) -> Duration { Duration::from_secs(days * 86400) }

    /// Return a [`Duration`] lasting the supplied number of weeks.
    pub fn weeks(weeks: u64) -> Duration { Self::days(weeks * 7) }
}

impl std::ops::Add<Duration> for DateTime {
    type Output = Result<DateTime>;

    /// Return a [`DateTime`] as a [`Result`] resulting from adding the `rhs` [`Duration`] to the
    /// object.
    ///
    /// # Errors
    ///
    /// Return an [`DateError::InvalidDate`] if adding the duration results in a bad date.
    fn add(self, rhs: Duration) -> Result<Self> {
        Ok(Self(
            self.0 + chrono::Duration::from_std(rhs).map_err(|_| DateError::InvalidDate)?
        ))
    }
}

impl std::ops::Sub<Self> for DateTime {
    type Output = Result<Duration>;

    /// Return the [`Duration`] as a [`Result`] resulting from subtracting the `rhs` from the
    /// object.
    ///
    /// # Errors
    ///
    /// Return an [`DateError::EntryOrder`] if the `rhs` is larger than the [`DateTime`].
    fn sub(self, rhs: Self) -> Result<Duration> {
        (self.0 - rhs.0).to_std().map_err(|_| DateError::EntryOrder)
    }
}

impl std::ops::Sub<Duration> for DateTime {
    type Output = Result<DateTime>;

    /// Return a [`DateTime`] as a [`Result`] resulting from subtracting the `rhs` [`Duration`]
    /// from the object.
    ///
    /// # Errors
    ///
    /// Return an [`DateError::InvalidDate`] if adding the duration results in a bad date.
    fn sub(self, rhs: Duration) -> Result<Self> {
        Ok(Self(
            self.0 - chrono::Duration::from_std(rhs).map_err(|_| DateError::InvalidDate)?
        ))
    }
}

impl std::str::FromStr for DateTime {
    type Err = DateError;

    /// Parse the [`DateTime`] out of a string, returning a [`Result`]
    ///
    /// # Errors
    ///
    /// If the datetime is not formatted as 'YYYY-MM-DD HH:MM:SS', returns an
    /// [`DateError::InvalidDate`]. Also if the datetime cannot be converted into a [`DateTime`],
    /// returns an [`DateError::InvalidDate`].
    #[rustfmt::skip]
    fn from_str(datetime: &str) -> Result<Self> {
        let Ok(parsed) = NaiveDateTime::parse_from_str(datetime, "%Y-%m-%d %H:%M:%S") else {
            return Err(DateError::InvalidDate);
        };
        Ok(Self(parsed))
    }
}

impl Display for DateTime {
    /// Format a [`DateTime`] object in "YYYY-MM-DD HH:MM:DD" format.
    #[rustfmt::skip]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}-{:02}-{:02} {:02}:{:02}:{:02}",
            self.0.year(), self.0.month(), self.0.day(),
            self.0.hour(), self.0.minute(), self.0.second())
    }
}

impl From<DateTime> for String {
    /// Convert a [`Date`] into a [`String`]
    fn from(datetime: DateTime) -> Self { datetime.to_string() }
}

#[cfg(test)]
mod tests {
    use assert2::{assert, let_assert};
    use rstest::rstest;

    use super::*;

    #[test]
    fn test_date_new() {
        let_assert!(Ok(date) = Date::new(2021, 11, 20));
        assert!(date.to_string() == String::from("2021-11-20"));
    }

    #[rstest]
    #[case(2021, 0,  20, "bad month zero")]
    #[case(2021, 13, 20, "bad month too high")]
    #[case(2021, 11, 0,  "bad day zero")]
    #[case(2021, 11, 32, "bad day too high")]
    fn test_date_new_unsuccess(
        #[case]year:  i32,
        #[case]month: u32,
        #[case]day:   u32,
        #[case]msg:   &str
    ) {
        assert!(Err(DateError::InvalidDate) == Date::new(year, month, day), "{msg}");
    }

    #[test]
    fn test_date_day_end() {
        let_assert!(Ok(date) = Date::new(2021, 11, 20));
        let_assert!(Ok(expected) = DateTime::new((2021, 11, 20), (23, 59, 59)));
        assert!(date.day_end() == expected);
    }

    #[test]
    fn test_date_day_start() {
        let_assert!(Ok(date) = Date::new(2021, 11, 20));
        let_assert!(Ok(expected) = DateTime::new((2021, 11, 20), (0, 0, 0)));
        assert!(date.day_start() == expected);
    }

    #[test]
    fn test_month_start() {
        let_assert!(Ok(date) = Date::new(2022, 11, 20));
        let_assert!(Ok(expected) = Date::new(2022, 11, 1));
        assert!(date.month_start() == expected);
    }

    #[rstest]
    #[case("jan", 1, 31)]
    #[case("feb", 2, 28)]
    #[case("mar", 3, 31)]
    #[case("apr", 4, 30)]
    #[case("may", 5, 31)]
    #[case("jun", 6, 30)]
    #[case("jul", 7, 31)]
    #[case("aug", 8, 31)]
    #[case("sep", 9, 30)]
    #[case("oct", 10, 31)]
    #[case("nov", 11, 30)]
    #[case("dec", 12, 31)]
    fn test_month_end(#[case]name: &str, #[case]mon: u32, #[case]day: u32) {
        let_assert!(Ok(date) = Date::new(2022, mon, 20));
        let_assert!(Ok(expected) = Date::new(2022, mon, day));
        assert!(date.month_end() == expected, "{name}");
    }

    #[test]
    fn test_month_end_leap_year() {
        let_assert!(Ok(date) = Date::new(2020, 2, 20));
        let_assert!(Ok(expected) = Date::new(2020, 2, 29));
        assert!(date.month_end() == expected);
    }

    #[test]
    fn test_date_week_start() {
        let_assert!(Ok(date) = Date::new(2022, 12, 20));
        let_assert!(Ok(expected) = Date::new(2022, 12, 18));
        assert!(date.week_start() == expected);
    }

    #[test]
    fn test_date_week_start_no_change() {
        let_assert!(Ok(date) = Date::new(2022, 12, 18));
        let_assert!(Ok(expected) = Date::new(2022, 12, 18));
        assert!(date.week_start() == expected);
    }

    #[test]
    fn test_date_week_end() {
        let_assert!(Ok(date) = Date::new(2022, 12, 15));
        let_assert!(Ok(expected) = Date::new(2022, 12, 17));
        assert!(date.week_end() == expected);
    }

    #[test]
    fn test_date_week_end_no_change() {
        let_assert!(Ok(date) = Date::new(2022, 12, 17));
        let_assert!(Ok(expected) = Date::new(2022, 12, 17));
        assert!(date.week_end() == expected);
    }

    #[test]
    fn test_date_year_start() {
        let_assert!(Ok(date) = Date::new(2022, 12, 20));
        let_assert!(Ok(expected) = Date::new(2022, 1, 1));
        assert!(date.year_start() == expected);
    }

    #[test]
    fn test_date_year_end() {
        let_assert!(Ok(date) = Date::new(2022, 12, 20));
        let_assert!(Ok(expected) = Date::new(2022, 12, 31));
        assert!(date.year_end() == expected);
    }

    #[test]
    fn test_date_succ() {
        let_assert!(Ok(date) = Date::new(2021, 11, 20));
        let_assert!(Ok(expected) = Date::new(2021, 11, 21));
        assert!(date.succ() == expected);
    }

    #[test]
    fn test_date_pred() {
        let_assert!(Ok(date) = Date::new(2021, 11, 20));
        let_assert!(Ok(expected) = Date::new(2021, 11, 19));
        assert!(date.pred() == expected);
    }

    #[test]
    fn test_date_parse() {
        let_assert!(Ok(date) = "2021-11-20".parse::<Date>());
        let_assert!(Ok(expected) = Date::new(2021, 11, 20));
        assert!(date == expected);
    }

    #[test]
    fn test_date_parse_bad() {
        let date = "fred".parse::<Date>();
        assert!(&date.is_err());
    }

    // DateRange

    #[test]
    fn test_date_range_default() {
        let range = DateRange::default();
        assert!(range.start() == Date::today());
        assert!(range.end() == Date::today().succ());
    }

    #[test]
    fn test_date_range_new_opt() {
        let_assert!(Some(range) = DateRange::new_opt(Date::today(), Date::today().succ()));
        assert!(range.start() == Date::today());
        assert!(range.end() == Date::today().succ());
    }

    #[test]
    fn test_date_range_new_opt_backwards() {
        let range = DateRange::new_opt(Date::today(), Date::today().pred());
        assert!(range.is_none());
    }

    #[test]
    fn test_date_range_new_opt_empty() {
        let range = DateRange::new_opt(Date::today(), Date::today());
        assert!(range.is_none());
    }

    #[test]
    fn test_date_range_new() {
        let range = DateRange::new(Date::today(), Date::today().succ());
        assert!(range.start() == Date::today());
        assert!(range.end() == Date::today().succ());
        assert!(range.is_empty() == false);
    }

    #[test]
    fn test_date_range_new_backwards() {
        let range = DateRange::new(Date::today(), Date::today().pred());
        assert!(range.start() == Date::today());
        assert!(range.end() == Date::today());
        assert!(range.is_empty() == true);
    }

    #[test]
    fn test_date_range_new_empty() {
        let range = DateRange::new(Date::today(), Date::today());
        assert!(range.start() == Date::today());
        assert!(range.end() == Date::today());
        assert!(range.is_empty() == true);
    }

    #[test]
    fn test_date_range_from_date() {
        let_assert!(Ok(date) = Date::new(2022, 12, 1));
        let range: DateRange = date.into();
        let expect = DateRange::new(date, date.succ());

        assert!(range == expect);
    }

    // DateTime

    #[test]
    fn test_datetime_new() {
        let_assert!(Ok(date) = DateTime::new((2021, 11, 20), (11, 32, 18)));
        assert!(date.to_string() == String::from("2021-11-20 11:32:18"));
    }

    #[test]
    fn test_datetime_new_bad_date() {
        let date = DateTime::new((2021, 13, 20), (11, 32, 18));
        assert!(date.is_err());
    }

    #[test]
    fn test_datetime_new_bad_time() {
        let date = DateTime::new((2021, 11, 20), (11, 82, 18));
        assert!(date.is_err());
    }

    #[test]
    fn test_datetime_parse() {
        let_assert!(Ok(date) = "2021-11-20 11:32:18".parse::<DateTime>());
        let_assert!(Ok(expected) = DateTime::new((2021, 11, 20), (11, 32, 18)));
        assert!(date == expected);
    }

    #[test]
    fn test_datetime_diff() {
        let_assert!(Ok(date) = DateTime::new((2021, 11, 20), (11, 32, 18)));
        let_assert!(Ok(old) = DateTime::new((2021, 11, 18), (12, 00, 00)));
        let_assert!(Ok(dur) = date - old);
        assert!(dur == Duration::from_secs(2 * 86400 - 28 * 60 + 18));
    }

    #[test]
    fn test_datetime_diff_bad() {
        let_assert!(Ok(date) = DateTime::new((2021, 11, 18), (12, 00, 00)));
        let_assert!(Ok(old) = DateTime::new((2021, 11, 20), (11, 32, 18)));
        let_assert!(Err(_) = date - old);
    }

    #[test]
    fn test_datetime_add_time() {
        let_assert!(Ok(date) = DateTime::new((2021, 11, 18), (12, 00, 00)));
        let_assert!(Ok(new) = date + DateTime::minutes(10));
        let_assert!(Ok(expected) = DateTime::new((2021, 11, 18), (12, 10, 00)));
        assert!(new == expected);
    }

    #[test]
    fn test_datetime_add_days() {
        let_assert!(Ok(date) = DateTime::new((2021, 11, 18), (12, 00, 00)));
        let_assert!(Ok(new) = date + DateTime::days(3));
        let_assert!(Ok(expected) = DateTime::new((2021, 11, 21), (12, 00, 00)));
        assert!(new == expected);
    }

    #[test]
    fn test_datetime_hhmm() {
        let_assert!(Ok(date) = DateTime::new((2021, 11, 18), (8, 5, 13)));
        assert!(date.hhmm() == String::from("08:05"));
    }

    #[test]
    fn test_datetime_parse_bad() {
        let date = "fred".parse::<DateTime>();
        assert!(&date.is_err());
    }
}