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
use chrono::{Datelike, DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc};

pub struct Calendar {
    year: i32,
    month: u32,
    day: u32,
    time: NaiveTime,
}

impl Calendar {
    pub fn from(time: DateTime<Utc>) -> Self {
        let date = time.date_naive();
        let time = time.time();
        Self { year: date.year(), month: date.month(), day: date.day(), time }
    }

    pub fn subtract_month(&mut self, count: u32) -> DateTime<Utc> {
        for _ in 0..count {
            self.month -= 1;
            if self.month == 0 {
                self.month = 12;
                self.year -= 1;
            }
        }
        return self.create_time();
    }

    pub fn subtract_year(&mut self, count: u32) -> DateTime<Utc> {
        for _ in 0..count {
            self.year -= 1;
        }
        return self.create_time();
    }

    fn create_time(&mut self) -> DateTime<Utc> {
        loop {
            if let Some(date) = NaiveDate::from_ymd_opt(self.year, self.month, self.day) {
                let time = DateTime::from_naive_utc_and_offset(NaiveDateTime::new(date, self.time), Utc);
                return time;
            }
            self.increment_day();
        }
    }

    fn increment_day(&mut self) {
        self.day += 1;
        if self.day > 31 {
            self.day = 1;
            self.month += 1;
            if self.month > 12 {
                self.month = 1;
                self.year += 1;
            }
        }
    }
}