1use std::fmt;
6use std::time::{SystemTime, UNIX_EPOCH, Duration};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10pub struct DateTime {
11 timestamp: u64, nanos: u32, }
14
15impl DateTime {
16 pub fn now() -> Self {
18 let duration = SystemTime::now()
19 .duration_since(UNIX_EPOCH)
20 .expect("System time before UNIX epoch");
21
22 Self {
23 timestamp: duration.as_secs(),
24 nanos: duration.subsec_nanos(),
25 }
26 }
27
28 pub fn from_timestamp(secs: u64, nanos: u32) -> Self {
30 Self {
31 timestamp: secs,
32 nanos,
33 }
34 }
35
36 pub fn timestamp(&self) -> u64 {
38 self.timestamp
39 }
40
41 pub fn nanos(&self) -> u32 {
43 self.nanos
44 }
45
46 pub fn to_rfc3339(&self) -> String {
48 let (year, month, day, hour, minute, second) = self.to_components();
49 format!(
50 "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
51 year, month, day, hour, minute, second
52 )
53 }
54
55 pub fn to_rfc2822(&self) -> String {
57 let (year, month, day, hour, minute, second) = self.to_components();
58 let weekday = self.weekday();
59 let month_name = month_name(month);
60
61 format!(
62 "{}, {} {} {} {:02}:{:02}:{:02} +0000",
63 weekday, day, month_name, year, hour, minute, second
64 )
65 }
66
67 pub fn format(&self, fmt: &str) -> String {
69 let (year, month, day, hour, minute, second) = self.to_components();
70
71 fmt.replace("%Y", &format!("{:04}", year))
72 .replace("%m", &format!("{:02}", month))
73 .replace("%d", &format!("{:02}", day))
74 .replace("%H", &format!("{:02}", hour))
75 .replace("%M", &format!("{:02}", minute))
76 .replace("%S", &format!("{:02}", second))
77 }
78
79 fn to_components(&self) -> (u32, u32, u32, u32, u32, u32) {
81 let days_since_epoch = self.timestamp / 86400;
83 let seconds_today = self.timestamp % 86400;
84
85 let hour = (seconds_today / 3600) as u32;
86 let minute = ((seconds_today % 3600) / 60) as u32;
87 let second = (seconds_today % 60) as u32;
88
89 let years_since_epoch = days_since_epoch / 365;
91 let year = 1970 + years_since_epoch as u32;
92
93 let days_this_year = days_since_epoch % 365;
94 let month = ((days_this_year / 30) + 1) as u32;
95 let day = ((days_this_year % 30) + 1) as u32;
96
97 (year, month, day, hour, minute, second)
98 }
99
100 pub fn add(&self, duration: Duration) -> Self {
102 let total_nanos = self.nanos as u64 + duration.subsec_nanos() as u64;
103 let extra_secs = total_nanos / 1_000_000_000;
104 let new_nanos = (total_nanos % 1_000_000_000) as u32;
105
106 Self {
107 timestamp: self.timestamp + duration.as_secs() + extra_secs,
108 nanos: new_nanos,
109 }
110 }
111
112 pub fn sub(&self, duration: Duration) -> Self {
114 let total_secs = duration.as_secs();
115 let nanos = duration.subsec_nanos();
116
117 if nanos > self.nanos {
118 Self {
119 timestamp: self.timestamp - total_secs - 1,
120 nanos: 1_000_000_000 + self.nanos - nanos,
121 }
122 } else {
123 Self {
124 timestamp: self.timestamp - total_secs,
125 nanos: self.nanos - nanos,
126 }
127 }
128 }
129
130 fn weekday(&self) -> &'static str {
132 let days_since_epoch = self.timestamp / 86400;
133 let weekday = (days_since_epoch + 4) % 7; match weekday {
135 0 => "Sun",
136 1 => "Mon",
137 2 => "Tue",
138 3 => "Wed",
139 4 => "Thu",
140 5 => "Fri",
141 6 => "Sat",
142 _ => "???",
143 }
144 }
145}
146
147fn month_name(month: u32) -> &'static str {
148 match month {
149 1 => "Jan",
150 2 => "Feb",
151 3 => "Mar",
152 4 => "Apr",
153 5 => "May",
154 6 => "Jun",
155 7 => "Jul",
156 8 => "Aug",
157 9 => "Sep",
158 10 => "Oct",
159 11 => "Nov",
160 12 => "Dec",
161 _ => "???",
162 }
163}
164
165impl Default for DateTime {
166 fn default() -> Self {
167 Self::now()
168 }
169}
170
171impl fmt::Display for DateTime {
172 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173 write!(f, "{}", self.to_rfc3339())
174 }
175}
176
177impl From<SystemTime> for DateTime {
178 fn from(st: SystemTime) -> Self {
179 let duration = st.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO);
180 Self {
181 timestamp: duration.as_secs(),
182 nanos: duration.subsec_nanos(),
183 }
184 }
185}
186
187impl From<DateTime> for SystemTime {
188 fn from(dt: DateTime) -> Self {
189 UNIX_EPOCH + Duration::new(dt.timestamp, dt.nanos)
190 }
191}
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196
197 #[test]
198 fn test_now() {
199 let now = DateTime::now();
200 assert!(now.timestamp() > 0);
201 }
202
203 #[test]
204 fn test_format() {
205 let dt = DateTime::from_timestamp(1640995200, 0); let formatted = dt.to_rfc3339();
207 assert!(formatted.contains("2022") || formatted.contains("2021")); }
209
210 #[test]
211 fn test_add_duration() {
212 let dt = DateTime::from_timestamp(1000, 0);
213 let dt2 = dt.add(Duration::from_secs(500));
214 assert_eq!(dt2.timestamp(), 1500);
215 }
216}
217
218#[cfg(feature = "serde")]
220impl avila_serde::Serialize for DateTime {
221 fn to_value(&self) -> avila_serde::Value {
222 avila_serde::Value::String(self.to_rfc3339())
224 }
225}
226
227#[cfg(feature = "serde")]
228impl avila_serde::Deserialize for DateTime {
229 fn from_value(value: avila_serde::Value) -> Result<Self, avila_serde::Error> {
230 match value {
231 avila_serde::Value::String(s) => {
232 if s.len() < 19 {
235 return Err(avila_serde::Error::Parse(format!("Invalid datetime format: {}", s)));
236 }
237
238 let parts: Vec<&str> = s.split('T').collect();
240 if parts.len() != 2 {
241 return Err(avila_serde::Error::Parse(format!("Invalid datetime format: {}", s)));
242 }
243
244 let date_parts: Vec<&str> = parts[0].split('-').collect();
245 let time_str = parts[1].trim_end_matches('Z');
246 let time_parts: Vec<&str> = time_str.split(':').collect();
247
248 if date_parts.len() != 3 || time_parts.len() != 3 {
249 return Err(avila_serde::Error::Parse(format!("Invalid datetime format: {}", s)));
250 }
251
252 let year: u32 = date_parts[0].parse()
253 .map_err(|_| avila_serde::Error::Parse(format!("Invalid year: {}", date_parts[0])))?;
254 let month: u32 = date_parts[1].parse()
255 .map_err(|_| avila_serde::Error::Parse(format!("Invalid month: {}", date_parts[1])))?;
256 let day: u32 = date_parts[2].parse()
257 .map_err(|_| avila_serde::Error::Parse(format!("Invalid day: {}", date_parts[2])))?;
258 let hour: u32 = time_parts[0].parse()
259 .map_err(|_| avila_serde::Error::Parse(format!("Invalid hour: {}", time_parts[0])))?;
260 let minute: u32 = time_parts[1].parse()
261 .map_err(|_| avila_serde::Error::Parse(format!("Invalid minute: {}", time_parts[1])))?;
262 let second: u32 = time_parts[2].parse()
263 .map_err(|_| avila_serde::Error::Parse(format!("Invalid second: {}", time_parts[2])))?;
264
265 let days_since_1970 = (year - 1970) * 365 + (month - 1) * 30 + (day - 1);
268 let seconds = (days_since_1970 as u64) * 86400
269 + (hour as u64) * 3600
270 + (minute as u64) * 60
271 + (second as u64);
272
273 Ok(Self::from_timestamp(seconds, 0))
274 }
275 _ => Err(avila_serde::Error::Parse("Expected string for DateTime".to_string()))
276 }
277 }
278}