1use std::fmt;
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
8pub struct Date {
9 year: i32,
10 month: u8,
11 day: u8,
12}
13
14impl Date {
15 pub fn new(year: i32, month: u8, day: u8) -> Option<Date> {
17 (1..=12).contains(&month).then_some(())?;
18 (day >= 1 && day <= days_in_month(year, month)).then_some(Date { year, month, day })
19 }
20
21 pub fn year(&self) -> i32 {
22 self.year
23 }
24
25 pub fn month(&self) -> u8 {
26 self.month
27 }
28
29 pub fn day(&self) -> u8 {
30 self.day
31 }
32
33 pub fn to_days(&self) -> i64 {
35 let (y, m, d) = (self.year as i64 - i64::from(self.month <= 2), self.month as i64, self.day as i64);
36 let era = y.div_euclid(400);
37 let yoe = y - era * 400;
38 let doy = (153 * (m + if m > 2 { -3 } else { 9 }) + 2) / 5 + d - 1;
39 era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468
40 }
41
42 pub fn from_days(days: i64) -> Option<Date> {
44 let z = days + 719_468;
45 let era = z.div_euclid(146_097);
46 let doe = z - era * 146_097;
47 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
48 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
49 let mp = (5 * doy + 2) / 153;
50 let d = (doy - (153 * mp + 2) / 5 + 1) as u8;
51 let m = if mp < 10 { mp + 3 } else { mp - 9 } as u8;
52 let y = yoe + era * 400 + i64::from(m <= 2);
53 Date::new(i32::try_from(y).ok()?, m, d)
54 }
55
56 pub fn today() -> Date {
58 DateTime::now().date
59 }
60
61 pub fn parse_iso(text: &str) -> Option<Date> {
63 let mut parts = text.trim().splitn(3, '-');
64 let y = parts.next()?.parse().ok()?;
65 let m = parts.next()?.parse().ok()?;
66 let d = parts.next()?.parse().ok()?;
67 Date::new(y, m, d)
68 }
69}
70
71impl fmt::Display for Date {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
74 }
75}
76
77#[cfg(feature = "serde")]
80impl serde::Serialize for Date {
81 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
82 serializer.collect_str(self)
83 }
84}
85
86#[cfg(feature = "serde")]
87impl<'de> serde::Deserialize<'de> for Date {
88 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
89 struct Iso;
90 impl serde::de::Visitor<'_> for Iso {
91 type Value = Date;
92 fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
93 f.write_str("uma data ISO (\"aaaa-mm-dd\")")
94 }
95 fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<Date, E> {
96 Date::parse_iso(text).ok_or_else(|| E::invalid_value(serde::de::Unexpected::Str(text), &self))
97 }
98 }
99 deserializer.deserialize_str(Iso)
100 }
101}
102
103#[cfg(feature = "chrono")]
105impl From<chrono::NaiveDate> for Date {
106 fn from(date: chrono::NaiveDate) -> Date {
107 use chrono::Datelike;
108 Date { year: date.year(), month: date.month() as u8, day: date.day() as u8 }
109 }
110}
111
112#[cfg(feature = "chrono")]
115impl From<Date> for chrono::NaiveDate {
116 fn from(date: Date) -> chrono::NaiveDate {
117 chrono::NaiveDate::from_ymd_opt(date.year, u32::from(date.month), u32::from(date.day))
118 .unwrap_or(if date.year < 0 { chrono::NaiveDate::MIN } else { chrono::NaiveDate::MAX })
119 }
120}
121
122pub fn is_leap_year(year: i32) -> bool {
123 (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
124}
125
126pub fn days_in_month(year: i32, month: u8) -> u8 {
127 match month {
128 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
129 4 | 6 | 9 | 11 => 30,
130 2 if is_leap_year(year) => 29,
131 2 => 28,
132 _ => 0,
133 }
134}
135
136#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
138pub struct Time {
139 hour: u8,
140 minute: u8,
141 second: u8,
142 millisecond: u16,
143}
144
145impl Time {
146 pub fn new(hour: u8, minute: u8, second: u8) -> Option<Time> {
147 Self::with_millis(hour, minute, second, 0)
148 }
149
150 pub fn with_millis(hour: u8, minute: u8, second: u8, millisecond: u16) -> Option<Time> {
151 (hour < 24 && minute < 60 && second < 60 && millisecond < 1000).then_some(Time { hour, minute, second, millisecond })
152 }
153
154 pub fn hour(&self) -> u8 {
155 self.hour
156 }
157
158 pub fn minute(&self) -> u8 {
159 self.minute
160 }
161
162 pub fn second(&self) -> u8 {
163 self.second
164 }
165
166 pub fn millisecond(&self) -> u16 {
167 self.millisecond
168 }
169
170 pub fn parse_iso(text: &str) -> Option<Time> {
172 let mut parts = text.trim().split(':');
173 let h = parts.next()?.parse().ok()?;
174 let m = parts.next()?.parse().ok()?;
175 let (s, ms) = match parts.next() {
176 None => (0, 0),
177 Some(s) => {
178 let (whole, frac) = s.split_once('.').unwrap_or((s, ""));
179 let digits: String = frac.chars().take(3).collect();
181 let ms = if digits.is_empty() { 0 } else { format!("{digits:0<3}").parse().ok()? };
182 (whole.parse().ok()?, ms)
183 }
184 };
185 if parts.next().is_some() {
186 return None;
187 }
188 Time::with_millis(h, m, s, ms)
189 }
190
191 fn seconds_of_day(&self) -> i64 {
192 self.hour as i64 * 3600 + self.minute as i64 * 60 + self.second as i64
193 }
194}
195
196impl fmt::Display for Time {
197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198 write!(f, "{:02}:{:02}:{:02}", self.hour, self.minute, self.second)
199 }
200}
201
202#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
204pub struct DateTime {
205 pub date: Date,
206 pub time: Time,
207}
208
209impl DateTime {
210 pub fn new(date: Date, time: Time) -> Self {
211 Self { date, time }
212 }
213
214 pub fn parse_iso(text: &str) -> Option<DateTime> {
218 let text = text.trim();
219 let (d, t) = text.split_once(['T', ' ']).unwrap_or((text, "00:00:00"));
220 let (t, offset) = split_offset(t)?;
221 let local = DateTime { date: Date::parse_iso(d)?, time: Time::parse_iso(t)? };
222 match offset {
223 None => Some(local),
224 Some(offset) => DateTime::from_unix_local(local.to_unix() - offset, local.time.millisecond()),
225 }
226 }
227
228 pub fn to_unix(&self) -> i64 {
230 self.date.to_days() * 86_400 + self.time.seconds_of_day()
231 }
232
233 pub fn from_unix(secs: i64, millisecond: u16) -> Option<DateTime> {
235 let date = Date::from_days(secs.div_euclid(86_400))?;
236 let s = secs.rem_euclid(86_400);
237 let time = Time::with_millis((s / 3600) as u8, (s / 60 % 60) as u8, (s % 60) as u8, millisecond)?;
238 Some(DateTime { date, time })
239 }
240
241 pub fn from_unix_local(utc: i64, millisecond: u16) -> Option<DateTime> {
244 DateTime::from_unix(utc + crate::platform::local_offset(utc), millisecond)
245 }
246
247 pub fn now() -> DateTime {
249 let since = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap_or_default();
250 DateTime::from_unix_local(since.as_secs() as i64, since.subsec_millis() as u16).expect("o relógio do sistema dá uma data válida")
251 }
252}
253
254#[doc(hidden)]
257pub fn split_offset(time: &str) -> Option<(&str, Option<i64>)> {
258 if let Some(t) = time.strip_suffix(['Z', 'z']) {
259 return Some((t, Some(0)));
260 }
261 let Some(at) = time.rfind(['+', '-']).filter(|&i| i > 0) else { return Some((time, None)) };
263 let (t, zone) = time.split_at(at);
264 let sign = if zone.starts_with('-') { -1 } else { 1 };
265 let digits: String = zone[1..].chars().filter(|c| *c != ':').collect();
266 let (h, m) = match digits.len() {
267 2 => (digits.parse::<i64>().ok()?, 0),
268 4 => (digits[..2].parse::<i64>().ok()?, digits[2..].parse::<i64>().ok()?),
269 _ => return None,
270 };
271 (h <= 14 && m < 60).then_some((t, Some(sign * (h * 3600 + m * 60))))
272}
273
274impl fmt::Display for DateTime {
275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276 write!(f, "{}T{}", self.date, self.time)
277 }
278}