1use serde::{Deserialize, Serialize};
6use std::fmt;
7
8#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default)]
24#[repr(transparent)]
25pub struct Date(i32);
26
27impl Date {
28 #[must_use]
32 pub fn from_ymd(year: i32, month: u32, day: u32) -> Option<Self> {
33 if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
34 return None;
35 }
36 let max_day = days_in_month(year, month);
38 if day > max_day {
39 return None;
40 }
41 Some(Self(days_from_civil(year, month, day)))
42 }
43
44 #[inline]
46 #[must_use]
47 pub const fn from_days(days: i32) -> Self {
48 Self(days)
49 }
50
51 #[inline]
53 #[must_use]
54 pub const fn as_days(self) -> i32 {
55 self.0
56 }
57
58 #[must_use]
60 pub fn year(self) -> i32 {
61 civil_from_days(self.0).0
62 }
63
64 #[must_use]
66 pub fn month(self) -> u32 {
67 civil_from_days(self.0).1
68 }
69
70 #[must_use]
72 pub fn day(self) -> u32 {
73 civil_from_days(self.0).2
74 }
75
76 #[must_use]
78 pub fn to_ymd(self) -> (i32, u32, u32) {
79 civil_from_days(self.0)
80 }
81
82 #[must_use]
84 pub fn parse(s: &str) -> Option<Self> {
85 let (negative, s) = if let Some(rest) = s.strip_prefix('-') {
87 (true, rest)
88 } else {
89 (false, s)
90 };
91
92 let parts: Vec<&str> = s.splitn(3, '-').collect();
93 if parts.len() != 3 {
94 return None;
95 }
96 let year: i32 = parts[0].parse().ok()?;
97 let month: u32 = parts[1].parse().ok()?;
98 let day: u32 = parts[2].parse().ok()?;
99 let year = if negative { -year } else { year };
100 Self::from_ymd(year, month, day)
101 }
102
103 #[must_use]
105 pub fn today() -> Self {
106 let ts = super::Timestamp::now();
107 ts.to_date()
108 }
109
110 #[must_use]
112 pub fn to_timestamp(self) -> super::Timestamp {
113 super::Timestamp::from_micros(self.0 as i64 * 86_400_000_000)
114 }
115
116 #[must_use]
121 pub fn add_duration(self, dur: &super::Duration) -> Self {
122 let (mut y, mut m, mut d) = self.to_ymd();
123
124 if dur.months() != 0 {
126 let total_months = y as i64 * 12 + (m as i64 - 1) + dur.months();
127 y = (total_months.div_euclid(12)) as i32;
128 m = (total_months.rem_euclid(12) + 1) as u32;
129 let max_d = days_in_month(y, m);
131 if d > max_d {
132 d = max_d;
133 }
134 }
135
136 let days = days_from_civil(y, m, d) as i64 + dur.days();
138 Self(days as i32)
139 }
140
141 #[must_use]
143 pub fn sub_duration(self, dur: &super::Duration) -> Self {
144 self.add_duration(&dur.neg())
145 }
146
147 #[must_use]
153 pub fn truncate(self, unit: &str) -> Option<Self> {
154 let (y, m, _d) = self.to_ymd();
155 match unit {
156 "year" => Self::from_ymd(y, 1, 1),
157 "month" => Self::from_ymd(y, m, 1),
158 "day" => Some(self),
159 _ => None,
160 }
161 }
162}
163
164impl fmt::Debug for Date {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 write!(f, "Date({})", self)
167 }
168}
169
170impl fmt::Display for Date {
171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172 let (y, m, d) = civil_from_days(self.0);
173 if y < 0 {
174 write!(f, "-{:04}-{:02}-{:02}", -y, m, d)
175 } else {
176 write!(f, "{:04}-{:02}-{:02}", y, m, d)
177 }
178 }
179}
180
181pub(crate) fn days_from_civil(year: i32, month: u32, day: u32) -> i32 {
188 let y = if month <= 2 { year - 1 } else { year } as i64;
189 let era = y.div_euclid(400);
190 let yoe = y.rem_euclid(400) as u32; let m = month;
192 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day - 1; let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; (era * 146097 + doe as i64 - 719468) as i32
195}
196
197pub(crate) fn civil_from_days(days: i32) -> (i32, u32, u32) {
199 let z = days as i64 + 719468;
200 let era = z.div_euclid(146097);
201 let doe = z.rem_euclid(146097) as u32; let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; let y = yoe as i64 + era * 400;
204 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let m = if mp < 10 { mp + 3 } else { mp - 9 }; let y = if m <= 2 { y + 1 } else { y };
209 (y as i32, m, d)
210}
211
212fn days_in_month(year: i32, month: u32) -> u32 {
214 match month {
215 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
216 4 | 6 | 9 | 11 => 30,
217 2 => {
218 if is_leap_year(year) {
219 29
220 } else {
221 28
222 }
223 }
224 _ => 0,
225 }
226}
227
228fn is_leap_year(year: i32) -> bool {
230 (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
231}
232
233#[cfg(test)]
234mod tests {
235 use super::*;
236
237 #[test]
238 fn test_epoch() {
239 let d = Date::from_ymd(1970, 1, 1).unwrap();
240 assert_eq!(d.as_days(), 0);
241 assert_eq!(d.year(), 1970);
242 assert_eq!(d.month(), 1);
243 assert_eq!(d.day(), 1);
244 }
245
246 #[test]
247 fn test_known_dates() {
248 let d = Date::from_ymd(2024, 1, 1).unwrap();
250 assert_eq!(d.as_days(), 19723);
251 assert_eq!(d.to_string(), "2024-01-01");
252
253 let d = Date::from_ymd(2000, 3, 1).unwrap();
255 assert_eq!(d.year(), 2000);
256 assert_eq!(d.month(), 3);
257 assert_eq!(d.day(), 1);
258 }
259
260 #[test]
261 fn test_roundtrip() {
262 for days in [-100000, -1, 0, 1, 10000, 19723, 50000] {
263 let d = Date::from_days(days);
264 let (y, m, day) = d.to_ymd();
265 let d2 = Date::from_ymd(y, m, day).unwrap();
266 assert_eq!(d, d2, "roundtrip failed for days={days}");
267 }
268 }
269
270 #[test]
271 fn test_parse() {
272 let d = Date::parse("2024-03-15").unwrap();
273 assert_eq!(d.year(), 2024);
274 assert_eq!(d.month(), 3);
275 assert_eq!(d.day(), 15);
276
277 assert!(Date::parse("not-a-date").is_none());
278 assert!(Date::parse("2024-13-01").is_none()); assert!(Date::parse("2024-02-30").is_none()); }
281
282 #[test]
283 fn test_display() {
284 assert_eq!(
285 Date::from_ymd(2024, 1, 5).unwrap().to_string(),
286 "2024-01-05"
287 );
288 assert_eq!(
289 Date::from_ymd(100, 12, 31).unwrap().to_string(),
290 "0100-12-31"
291 );
292 }
293
294 #[test]
295 fn test_ordering() {
296 let d1 = Date::from_ymd(2024, 1, 1).unwrap();
297 let d2 = Date::from_ymd(2024, 6, 15).unwrap();
298 assert!(d1 < d2);
299 }
300
301 #[test]
302 fn test_leap_year() {
303 assert!(Date::from_ymd(2000, 2, 29).is_some()); assert!(Date::from_ymd(1900, 2, 29).is_none()); assert!(Date::from_ymd(2024, 2, 29).is_some()); assert!(Date::from_ymd(2023, 2, 29).is_none()); }
308
309 #[test]
310 fn test_to_timestamp() {
311 let d = Date::from_ymd(1970, 1, 2).unwrap();
312 assert_eq!(d.to_timestamp().as_micros(), 86_400_000_000);
313 }
314
315 #[test]
316 fn test_truncate() {
317 let d = Date::from_ymd(2024, 6, 15).unwrap();
318
319 let year = d.truncate("year").unwrap();
320 assert_eq!(year.to_string(), "2024-01-01");
321
322 let month = d.truncate("month").unwrap();
323 assert_eq!(month.to_string(), "2024-06-01");
324
325 let day = d.truncate("day").unwrap();
326 assert_eq!(day, d);
327
328 assert!(d.truncate("hour").is_none());
329 }
330
331 #[test]
332 fn test_negative_year() {
333 let d = Date::parse("-0001-01-01").unwrap();
334 assert_eq!(d.year(), -1);
335 assert_eq!(d.to_string(), "-0001-01-01");
336 }
337}