date_time 2.2.0

Date_Time is a high-level rust library for use in situations where precision beyond seconds is not necessary.
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
use date_utils;
use month_tuple::MonthTuple;
use regex::Regex;
use std::cmp::Ordering;
use std::fmt;
use std::str::FromStr;

const DAYS_IN_A_COMMON_YEAR: u32 = 365;
const DAYS_IN_A_LEAP_YEAR: u32 = 366;

pub type Date = DateTuple;

/// Holds a specific date by year, month, and day.
///
/// Handles values from 01 Jan 0000 to 31 Dec 9999.
#[cfg_attr(
    feature = "serde_support",
    derive(serde::Serialize, serde::Deserialize)
)]
#[derive(PartialEq, Eq, Debug, Copy, Clone, Hash)]
pub struct DateTuple {
    y: u16,
    m: u8,
    d: u8,
}

impl DateTuple {
    /// Takes a year, month, and day and converts them into a DateTuple.
    ///
    /// Will not overlap - the date entered must be valid without further calculation.
    pub fn new(y: u16, m: u8, d: u8) -> Result<DateTuple, String> {
        if y > 9999 {
            return Err(format!(
                "Invalid year in DateTuple {:?}: year must be <= 9999.",
                DateTuple { y, m, d }
            ));
        }
        if (1..=12).contains(&m) {
            if d == 0 || d > date_utils::get_last_date_in_month(m, y) {
                return Err(format!(
                    "Invalid date in DateTuple: {:?}",
                    DateTuple { y, m, d }
                ));
            }
            Ok(DateTuple { y, m, d })
        } else {
            Err(format!(
                "Invalid month in DateTuple: {:?}\nMonth must be between 1 and 12; Note that months are ONE-BASED since version 2.0.0.",
                DateTuple { y, m, d }
            ))
        }
    }

    /// Returns the minimum date handled - 1st January 0000.
    pub fn min_value() -> DateTuple {
        DateTuple::new(0, 1, 1).unwrap()
    }

    /// Returns the maximum date handled - 31st December 9999.
    pub fn max_value() -> DateTuple {
        DateTuple::new(9999, 12, 31).unwrap()
    }

    /// Returns a `DateTuple` of the current date according to the system clock.
    pub fn today() -> DateTuple {
        date_utils::now_as_datetuple()
    }

    pub fn get_year(self) -> u16 {
        self.y
    }

    pub fn get_month(self) -> u8 {
        self.m
    }

    pub fn get_date(self) -> u8 {
        self.d
    }

    /// Gets a DateTuple representing the date immediately following
    /// the current one. Will not go past Dec 9999.
    pub fn next_date(self) -> DateTuple {
        if self.y == 9999 && self.m == 12 && self.d == 31 {
            return self;
        }
        if self.d == date_utils::get_last_date_in_month(self.m, self.y) {
            if self.m == 12 {
                DateTuple {
                    y: self.y + 1,
                    m: 1,
                    d: 1,
                }
            } else {
                DateTuple {
                    y: self.y,
                    m: self.m + 1,
                    d: 1,
                }
            }
        } else {
            DateTuple {
                y: self.y,
                m: self.m,
                d: self.d + 1,
            }
        }
    }

    /// Gets a DateTuple representing the date immediately preceding
    /// the current one. Will not go past 1 Jan 0000.
    pub fn previous_date(self) -> DateTuple {
        if self.y == 0 && self.m == 1 && self.d == 1 {
            return self;
        }
        if self.d == 1 {
            if self.m == 1 {
                DateTuple {
                    y: self.y - 1,
                    m: 12,
                    d: date_utils::get_last_date_in_month(12, self.y - 1),
                }
            } else {
                DateTuple {
                    y: self.y,
                    m: self.m - 1,
                    d: date_utils::get_last_date_in_month(self.m - 1, self.y),
                }
            }
        } else {
            DateTuple {
                y: self.y,
                m: self.m,
                d: self.d - 1,
            }
        }
    }

    /// Adds a number of days to a DateTuple.
    pub fn add_days(&mut self, days: u32) {
        for _ in 0..days {
            *self = self.next_date();
        }
    }

    /// Subtracts a number of days from a DateTuple.
    pub fn subtract_days(&mut self, days: u32) {
        for _ in 0..days {
            *self = self.previous_date();
        }
    }

    /// Adds a number of months to a DateTuple.
    ///
    /// If the day of month is beyond the last date in the resulting month, the day of
    /// month will be set to the last day of that month.
    pub fn add_months(&mut self, months: u32) {
        let mut new_month = MonthTuple::from(*self);
        new_month.add_months(months);
        let last_date_in_month =
            date_utils::get_last_date_in_month(new_month.get_month(), new_month.get_year());
        if self.d > last_date_in_month {
            self.d = last_date_in_month;
        }
        self.y = new_month.get_year();
        self.m = new_month.get_month();
    }

    /// Subtracts a number of months from a DateTuple.
    ///
    /// If the day of month is beyond the last date in the resulting month, the day of
    /// month will be set to the last day of that month.
    pub fn subtract_months(&mut self, months: u32) {
        let mut new_month = MonthTuple::from(*self);
        new_month.subtract_months(months);
        let last_date_in_month =
            date_utils::get_last_date_in_month(new_month.get_month(), new_month.get_year());
        if self.d > last_date_in_month {
            self.d = last_date_in_month;
        }
        self.y = new_month.get_year();
        self.m = new_month.get_month();
    }

    /// Adds a number of years to a DateTuple.
    ///
    /// If the date is set to Feb 29 and the resulting year is not a leap year,
    /// it will be changed to Feb 28.
    pub fn add_years(&mut self, years: u16) {
        let mut new_years = self.y + years;
        if new_years > 9999 {
            new_years = 9999;
        }
        if self.m == 2 && self.d == 29 && !date_utils::is_leap_year(new_years) {
            self.d = 28
        }
        self.y = new_years;
    }

    /// Subtracts a number of years from a DateTuple.
    ///
    /// If the date is set to Feb 29 and the resulting year is not a leap year,
    /// it will be changed to Feb 28.
    pub fn subtract_years(&mut self, years: u16) {
        let mut new_years = i32::from(self.y) - i32::from(years);
        if new_years < 0 {
            new_years = 0;
        }
        let new_years = new_years as u16;
        if self.m == 2 && self.d == 29 && !date_utils::is_leap_year(new_years) {
            self.d = 28
        }
        self.y = new_years;
    }

    /// Produces a readable date.
    ///
    /// ## Examples
    /// * 2 Oct 2018
    /// * 13 Jan 2019
    pub fn to_readable_string(self) -> String {
        let month = MonthTuple::from(self);
        format!("{} {}", self.d, month.to_readable_string())
    }

    /// Gets the total number of days in the tuple,
    /// with the first being `DateTuple::min_value()`.
    pub fn to_days(self) -> u32 {
        let mut total_days = 0u32;
        for y in 0..self.y {
            total_days += if date_utils::is_leap_year(y) {
                DAYS_IN_A_LEAP_YEAR
            } else {
                DAYS_IN_A_COMMON_YEAR
            }
        }
        for m in 1..self.m {
            total_days += u32::from(date_utils::get_last_date_in_month(m, self.y));
        }
        total_days + u32::from(self.d)
    }

    /// Calculates years, months, and days from a total number of
    /// days, with the first being `DateTuple::min_value()`.
    pub fn from_days(mut total_days: u32) -> Result<DateTuple, String> {
        let mut years = 0u16;
        let mut months = 1u8;
        while total_days
            > if date_utils::is_leap_year(years) {
                DAYS_IN_A_LEAP_YEAR
            } else {
                DAYS_IN_A_COMMON_YEAR
            }
        {
            total_days -= if date_utils::is_leap_year(years) {
                DAYS_IN_A_LEAP_YEAR
            } else {
                DAYS_IN_A_COMMON_YEAR
            };
            years += 1;
        }
        while total_days > u32::from(date_utils::get_last_date_in_month(months, years)) {
            total_days -= u32::from(date_utils::get_last_date_in_month(months, years));
            months += 1;
        }
        DateTuple::new(years, months, total_days as u8)
    }
}

impl fmt::Display for DateTuple {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:04}-{:02}-{:02}", self.y, self.m, self.d)
    }
}

impl FromStr for DateTuple {
    type Err = String;

    /// Expects a string formatted like 2018-11-02.
    ///
    /// Also accepts the legacy crate format of 20181102.
    fn from_str(s: &str) -> Result<DateTuple, Self::Err> {
        lazy_static! {
            static ref VALID_FORMAT: Regex = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
            static ref LEGACY_FORMAT: Regex = Regex::new(r"^\d{8}$").unwrap();
        }

        if VALID_FORMAT.is_match(s) {
            match DateTuple::new(
                u16::from_str(&s[0..4]).unwrap(),
                u8::from_str(&s[5..7]).unwrap(),
                u8::from_str(&s[8..10]).unwrap(),
            ) {
                Ok(d) => Ok(d),
                Err(e) => Err(format!("Invalid date passed to from_str: {}", e)),
            }
        } else if LEGACY_FORMAT.is_match(s) {
            let (s1, s2) = s.split_at(4);
            let (s2, s3) = s2.split_at(2);
            match DateTuple::new(
                u16::from_str(s1).unwrap(),
                u8::from_str(s2).unwrap(),
                u8::from_str(s3).unwrap(),
            ) {
                Ok(d) => Ok(d),
                Err(e) => Err(format!("Invalid date passed to from_str: {}", e)),
            }
        } else {
            Err(format!("Invalid str formatting of DateTuple: {}\nExpects a string formatted like 2018-11-02.", s))
        }
    }
}

impl PartialOrd for DateTuple {
    fn partial_cmp(&self, other: &DateTuple) -> Option<Ordering> {
        if self.y == other.y {
            if self.m == other.m {
                self.d.partial_cmp(&other.d)
            } else {
                self.m.partial_cmp(&other.m)
            }
        } else {
            self.y.partial_cmp(&other.y)
        }
    }
}

#[cfg_attr(tarpaulin, skip)]
impl Ord for DateTuple {
    fn cmp(&self, other: &DateTuple) -> Ordering {
        if self.y == other.y {
            if self.m == other.m {
                self.d.cmp(&other.d)
            } else {
                self.m.cmp(&other.m)
            }
        } else {
            self.y.cmp(&other.y)
        }
    }
}

#[cfg(test)]
mod tests {

    use super::Date;

    #[test]
    fn test_next_date() {
        let tuple1 = Date::new(2000, 6, 10).unwrap();
        let tuple2 = Date::new(2000, 3, 31).unwrap();
        let tuple3 = Date::max_value();
        assert_eq!(
            Date {
                y: 2000,
                m: 6,
                d: 11
            },
            tuple1.next_date()
        );
        assert_eq!(
            Date {
                y: 2000,
                m: 4,
                d: 1
            },
            tuple2.next_date()
        );
        assert_eq!(
            Date {
                y: 9999,
                m: 12,
                d: 31
            },
            tuple3.next_date()
        );
    }

    #[test]
    fn test_previous_date() {
        let tuple1 = Date::new(2000, 6, 10).unwrap();
        let tuple2 = Date::new(2000, 3, 1).unwrap();
        let tuple3 = Date::new(0, 1, 1).unwrap();
        let tuple4 = Date::new(2000, 1, 1).unwrap();
        assert_eq!(
            Date {
                y: 2000,
                m: 6,
                d: 9
            },
            tuple1.previous_date()
        );
        assert_eq!(
            Date {
                y: 2000,
                m: 2,
                d: 29
            },
            tuple2.previous_date()
        );
        assert_eq!(Date { y: 0, m: 1, d: 1 }, tuple3.previous_date());
        assert_eq!(
            Date {
                y: 1999,
                m: 12,
                d: 31
            },
            tuple4.previous_date()
        );
    }
}