1use std::fmt::{Display, Formatter, Write};
16
17use chrono::{Datelike, Days, LocalResult, Months, NaiveDate, NaiveTime, TimeDelta, TimeZone};
18use serde::{Deserialize, Serialize};
19use serde_json::Value;
20use snafu::ResultExt;
21
22use crate::Timezone;
23use crate::error::{InvalidDateStrSnafu, ParseDateStrSnafu, Result};
24use crate::interval::{IntervalDayTime, IntervalMonthDayNano, IntervalYearMonth};
25use crate::timezone::get_timezone;
26use crate::util::datetime_to_utc;
27
28const UNIX_EPOCH_FROM_CE: i32 = 719_163;
29
30#[derive(
33 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Deserialize, Serialize,
34)]
35pub struct Date(i32);
36
37impl From<Date> for Value {
38 fn from(d: Date) -> Self {
39 Value::String(d.to_string())
40 }
41}
42
43impl From<i32> for Date {
44 fn from(v: i32) -> Self {
45 Self(v)
46 }
47}
48
49impl From<NaiveDate> for Date {
50 fn from(date: NaiveDate) -> Self {
51 Self(date.num_days_from_ce() - UNIX_EPOCH_FROM_CE)
52 }
53}
54
55impl Display for Date {
56 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
58 if let Some(abs_date) = NaiveDate::from_num_days_from_ce_opt(UNIX_EPOCH_FROM_CE + self.0) {
59 write!(f, "{}", abs_date.format("%F"))
60 } else {
61 write!(f, "Date({})", self.0)
62 }
63 }
64}
65
66impl Date {
67 pub fn from_str_utc(s: &str) -> Result<Self> {
69 Self::from_str(s, None)
70 }
71
72 pub fn from_str(s: &str, timezone: Option<&Timezone>) -> Result<Self> {
74 let s = s.trim();
75 let date = NaiveDate::parse_from_str(s, "%F").context(ParseDateStrSnafu { raw: s })?;
76 let Some(timezone) = timezone else {
77 return Ok(Self(date.num_days_from_ce() - UNIX_EPOCH_FROM_CE));
78 };
79
80 let datetime = date.and_time(NaiveTime::default());
81 match datetime_to_utc(&datetime, timezone) {
82 LocalResult::None => InvalidDateStrSnafu { raw: s }.fail(),
83 LocalResult::Single(utc) | LocalResult::Ambiguous(utc, _) => Ok(Date::from(utc.date())),
84 }
85 }
86
87 pub fn new(val: i32) -> Self {
88 Self(val)
89 }
90
91 pub fn val(&self) -> i32 {
92 self.0
93 }
94
95 pub fn to_chrono_date(&self) -> Option<NaiveDate> {
96 NaiveDate::from_num_days_from_ce_opt(UNIX_EPOCH_FROM_CE + self.0)
97 }
98
99 pub fn as_formatted_string(
102 self,
103 pattern: &str,
104 timezone: Option<&Timezone>,
105 ) -> Result<Option<String>> {
106 if let Some(v) = self.to_chrono_date() {
107 let time = NaiveTime::from_hms_nano_opt(0, 0, 0, 0).unwrap();
109 let v = v.and_time(time);
110 let mut formatted = String::new();
111
112 match get_timezone(timezone) {
113 Timezone::Offset(offset) => {
114 write!(
115 formatted,
116 "{}",
117 offset.from_utc_datetime(&v).format(pattern)
118 )
119 .context(crate::error::FormatSnafu { pattern })?;
120 }
121 Timezone::Named(tz) => {
122 write!(formatted, "{}", tz.from_utc_datetime(&v).format(pattern))
123 .context(crate::error::FormatSnafu { pattern })?;
124 }
125 }
126
127 return Ok(Some(formatted));
128 }
129
130 Ok(None)
131 }
132
133 pub fn to_secs(&self) -> i64 {
134 (self.0 as i64) * 24 * 3600
135 }
136
137 pub fn add_year_month(&self, interval: IntervalYearMonth) -> Option<Date> {
140 let naive_date = self.to_chrono_date()?;
141
142 naive_date
143 .checked_add_months(Months::new(interval.months as u32))
144 .map(Into::into)
145 }
146
147 pub fn add_day_time(&self, interval: IntervalDayTime) -> Option<Date> {
149 let naive_date = self.to_chrono_date()?;
150
151 naive_date
152 .checked_add_days(Days::new(interval.days as u64))?
153 .checked_add_signed(TimeDelta::milliseconds(interval.milliseconds as i64))
154 .map(Into::into)
155 }
156
157 pub fn add_month_day_nano(&self, interval: IntervalMonthDayNano) -> Option<Date> {
159 let naive_date = self.to_chrono_date()?;
160
161 naive_date
162 .checked_add_months(Months::new(interval.months as u32))?
163 .checked_add_days(Days::new(interval.days as u64))?
164 .checked_add_signed(TimeDelta::nanoseconds(interval.nanoseconds))
165 .map(Into::into)
166 }
167
168 pub fn sub_year_month(&self, interval: IntervalYearMonth) -> Option<Date> {
170 let naive_date = self.to_chrono_date()?;
171
172 naive_date
173 .checked_sub_months(Months::new(interval.months as u32))
174 .map(Into::into)
175 }
176
177 pub fn sub_day_time(&self, interval: IntervalDayTime) -> Option<Date> {
179 let naive_date = self.to_chrono_date()?;
180
181 naive_date
182 .checked_sub_days(Days::new(interval.days as u64))?
183 .checked_sub_signed(TimeDelta::milliseconds(interval.milliseconds as i64))
184 .map(Into::into)
185 }
186
187 pub fn sub_month_day_nano(&self, interval: IntervalMonthDayNano) -> Option<Date> {
189 let naive_date = self.to_chrono_date()?;
190
191 naive_date
192 .checked_sub_months(Months::new(interval.months as u32))?
193 .checked_sub_days(Days::new(interval.days as u64))?
194 .checked_sub_signed(TimeDelta::nanoseconds(interval.nanoseconds))
195 .map(Into::into)
196 }
197
198 pub fn negative(&self) -> Self {
199 Self(-self.0)
200 }
201
202 pub fn checked_negative(&self) -> Option<Self> {
203 self.0.checked_neg().map(Self)
204 }
205}
206
207#[cfg(test)]
208mod tests {
209 use chrono::Utc;
210
211 use super::*;
212
213 #[test]
214 pub fn test_print_date2() {
215 assert_eq!("1969-12-31", Date::new(-1).to_string());
216 assert_eq!("1970-01-01", Date::new(0).to_string());
217 assert_eq!("1970-02-12", Date::new(42).to_string());
218 }
219
220 #[test]
221 pub fn test_date_parse() {
222 assert_eq!(
223 "1970-01-01",
224 Date::from_str("1970-01-01", None).unwrap().to_string()
225 );
226
227 assert_eq!(
228 "1969-01-01",
229 Date::from_str("1969-01-01", None).unwrap().to_string()
230 );
231
232 assert_eq!(
233 "1969-01-01",
234 Date::from_str(" 1969-01-01 ", None)
235 .unwrap()
236 .to_string()
237 );
238
239 let now = Utc::now().date_naive().format("%F").to_string();
240 assert_eq!(now, Date::from_str(&now, None).unwrap().to_string());
241
242 assert_eq!(
244 "1969-12-31",
245 Date::from_str(
246 "1970-01-01",
247 Some(&Timezone::from_tz_string("Asia/Shanghai").unwrap())
248 )
249 .unwrap()
250 .to_string()
251 );
252
253 assert_eq!(
254 "1969-12-31",
255 Date::from_str(
256 "1970-01-01",
257 Some(&Timezone::from_tz_string("+16:00").unwrap())
258 )
259 .unwrap()
260 .to_string()
261 );
262
263 assert_eq!(
264 "1970-01-01",
265 Date::from_str(
266 "1970-01-01",
267 Some(&Timezone::from_tz_string("-8:00").unwrap())
268 )
269 .unwrap()
270 .to_string()
271 );
272
273 assert_eq!(
274 "1970-01-01",
275 Date::from_str(
276 "1970-01-01",
277 Some(&Timezone::from_tz_string("-16:00").unwrap())
278 )
279 .unwrap()
280 .to_string()
281 );
282 }
283
284 #[test]
285 fn test_add_sub_interval() {
286 let date = Date::new(1000);
287
288 let interval = IntervalYearMonth::new(3);
289
290 let new_date = date.add_year_month(interval).unwrap();
291 assert_eq!(new_date.val(), 1091);
292
293 assert_eq!(date, new_date.sub_year_month(interval).unwrap());
294 }
295
296 #[test]
297 pub fn test_min_max() {
298 let mut date = Date::from_str("9999-12-31", None).unwrap();
299 date.0 += 1000;
300 assert_eq!(date, Date::from_str(&date.to_string(), None).unwrap());
301 }
302
303 #[test]
304 fn test_as_formatted_string() {
305 let d: Date = 42.into();
306
307 assert_eq!(
308 "1970-02-12",
309 d.as_formatted_string("%Y-%m-%d", None).unwrap().unwrap()
310 );
311 assert_eq!(
312 "1970-02-12 00:00:00",
313 d.as_formatted_string("%Y-%m-%d %H:%M:%S", None)
314 .unwrap()
315 .unwrap()
316 );
317 assert_eq!(
318 "1970-02-12T00:00:00:000",
319 d.as_formatted_string("%Y-%m-%dT%H:%M:%S:%3f", None)
320 .unwrap()
321 .unwrap()
322 );
323 assert_eq!(
324 "1970-02-12T08:00:00:000",
325 d.as_formatted_string(
326 "%Y-%m-%dT%H:%M:%S:%3f",
327 Some(&Timezone::from_tz_string("Asia/Shanghai").unwrap())
328 )
329 .unwrap()
330 .unwrap()
331 );
332 }
333
334 #[test]
335 pub fn test_from() {
336 let d: Date = 42.into();
337 assert_eq!(42, d.val());
338 }
339
340 #[test]
341 fn test_to_secs() {
342 let d = Date::from_str("1970-01-01", None).unwrap();
343 assert_eq!(d.to_secs(), 0);
344 let d = Date::from_str("1970-01-02", None).unwrap();
345 assert_eq!(d.to_secs(), 24 * 3600);
346 let d = Date::from_str("1970-01-03", None).unwrap();
347 assert_eq!(d.to_secs(), 2 * 24 * 3600);
348 }
349}