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
use chrono::{Datelike, NaiveDate};
use super::domain::CalendarUnit;
pub fn convert_to_year(date: NaiveDate) -> CalendarUnit {
CalendarUnit::Year(date.year())
}
pub fn convert_to_quarter(date: NaiveDate) -> CalendarUnit {
CalendarUnit::Quarter(
date.year(),
((date.month() - 1) / 3 + 1).try_into().unwrap(),
)
}
pub fn convert_to_half(date: NaiveDate) -> CalendarUnit {
CalendarUnit::Half(
date.year(),
((date.month() - 1) / 6 + 1).try_into().unwrap(),
)
}
pub fn convert_to_month(date: NaiveDate) -> CalendarUnit {
CalendarUnit::Month(date.year(), date.month().try_into().unwrap())
}
pub fn convert_to_iso_week(date: NaiveDate) -> CalendarUnit {
CalendarUnit::Week(date.year(), date.iso_week().week().try_into().unwrap())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_convert_week() {
assert_eq!(
convert_to_iso_week(NaiveDate::from_ymd(2020, 2, 29)),
CalendarUnit::Week(2020, 9)
);
assert_eq!(
convert_to_iso_week(NaiveDate::from_ymd(2022, 12, 31)),
CalendarUnit::Week(2022, 52)
)
}
#[test]
fn test_convert_month() {
assert_eq!(
convert_to_month(NaiveDate::from_ymd(2020, 2, 29)),
CalendarUnit::Month(2020, 2)
);
assert_eq!(
convert_to_month(NaiveDate::from_ymd(2022, 12, 31)),
CalendarUnit::Month(2022, 12)
)
}
#[test]
fn test_convert_quarter() {
assert_eq!(
convert_to_quarter(NaiveDate::from_ymd(2020, 2, 29)),
CalendarUnit::Quarter(2020, 1)
);
assert_eq!(
convert_to_quarter(NaiveDate::from_ymd(2022, 12, 31)),
CalendarUnit::Quarter(2022, 4)
)
}
#[test]
fn test_convert_half() {
assert_eq!(
convert_to_half(NaiveDate::from_ymd(2020, 2, 29)),
CalendarUnit::Half(2020, 1)
);
assert_eq!(
convert_to_half(NaiveDate::from_ymd(2022, 12, 31)),
CalendarUnit::Half(2022, 2)
)
}
#[test]
fn test_convert_year() {
assert_eq!(
convert_to_year(NaiveDate::from_ymd(2020, 2, 29)),
CalendarUnit::Year(2020)
);
assert_eq!(
convert_to_year(NaiveDate::from_ymd(2022, 12, 31)),
CalendarUnit::Year(2022)
)
}
}