carbono/alter/
start.rs

1use chrono::{Datelike, Timelike};
2
3use crate::Carbono;
4
5impl Carbono {
6    pub fn start_year(&self) -> Self {
7        Carbono {
8            datetime: self.datetime
9                .with_month(1)
10                .unwrap()
11                .with_day(1)
12                .unwrap()
13                .with_hour(0)
14                .unwrap()
15                .with_minute(0)
16                .unwrap()
17                .with_second(0)
18                .unwrap()
19        }
20    }
21
22    pub fn start_month(&self) -> Self {
23        Carbono {
24            datetime: self.datetime
25                .with_day(1)
26                .unwrap()
27                .with_hour(0)
28                .unwrap()
29                .with_minute(0)
30                .unwrap()
31                .with_second(0)
32                .unwrap()
33        }
34    }
35
36    pub fn start_day(&self) -> Self {
37        Carbono {
38            datetime: self.datetime
39                .with_hour(0)
40                .unwrap()
41                .with_minute(0)
42                .unwrap()
43                .with_second(0)
44                .unwrap()
45        }
46    }
47
48    pub fn start_hour(&self) -> Self {
49        Carbono {
50            datetime: self.datetime
51                .with_minute(0)
52                .unwrap()
53                .with_second(0)
54                .unwrap()
55        }
56    }
57
58    pub fn start_minute(&self) -> Self {
59        Carbono {
60            datetime: self.datetime
61                .with_second(0)
62                .unwrap()
63        }
64    }
65}
66
67#[cfg(test)]
68mod tests {
69    use chrono::prelude::*;
70    use super::*;
71
72    #[test]
73    fn it_can_move_to_the_start_of_the_year() {
74        let carbono = Carbono::now().start_year();
75
76        assert_eq!(carbono.datetime, Utc.with_ymd_and_hms(2022, 1, 1, 0, 0, 0).unwrap());
77    }
78
79    #[test]
80    fn it_can_move_to_the_start_of_the_month() {
81        let carbono = Carbono::now().start_month();
82
83        assert_eq!(carbono.datetime, Utc.with_ymd_and_hms(2022, 12, 1, 0, 0, 0).unwrap());
84    }
85
86    #[test]
87    fn it_can_move_to_the_start_of_the_day() {
88        let carbono = Carbono::now().start_day();
89
90        assert_eq!(carbono.datetime, Utc.with_ymd_and_hms(2022, 12, 15, 0, 0, 0).unwrap());
91    }
92
93    #[test]
94    fn it_can_move_to_the_start_of_the_hour() {
95        let carbono = Carbono::now().start_hour();
96
97        assert_eq!(carbono.datetime, Utc.with_ymd_and_hms(2022, 12, 15, 12, 0, 0).unwrap());
98    }
99
100    #[test]
101    fn it_can_move_to_the_start_of_the_minute() {
102        let carbono = Carbono::now().start_minute();
103
104        assert_eq!(carbono.datetime, Utc.with_ymd_and_hms(2022, 12, 15, 12, 30, 0).unwrap());
105    }
106}