1use chrono::{
4 DateTime, Days, Duration, NaiveDate, NaiveDateTime, NaiveTime, SecondsFormat, TimeZone, Utc,
5};
6
7const DATE_FORMAT: &str = "%Y-%m-%d";
8const SECOND_OUTPUT: &str = "%Y-%m-%dT%H:%M:%S";
9const MINUTE_OUTPUT: &str = "%Y-%m-%dT%H:%M";
10const DATETIME_FORMATS: [&str; 3] = [SECOND_OUTPUT, MINUTE_OUTPUT, "%Y-%m-%d %H:%M"];
11
12pub fn parse_date(s: &str, range_end: bool) -> Result<DateTime<Utc>, String> {
14 parse_date_in(s, range_end, &Utc)
15}
16
17pub fn parse_date_in<Z: TimeZone>(
22 s: &str,
23 range_end: bool,
24 zone: &Z,
25) -> Result<DateTime<Utc>, String> {
26 let s = s.trim();
27 if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
28 return Ok(dt.with_timezone(&Utc));
29 }
30 if let Some(naive) = DATETIME_FORMATS
31 .iter()
32 .find_map(|format| NaiveDateTime::parse_from_str(s, format).ok())
33 {
34 return Ok(naive.and_utc());
35 }
36 let date = NaiveDate::parse_from_str(s, DATE_FORMAT)
37 .map_err(|e| format!("invalid date '{s}': {e}"))?;
38 let bound = if range_end {
39 date.checked_add_days(Days::new(1))
40 .and_then(|next| day_start(zone, next))
41 .and_then(|start| start.checked_sub_signed(Duration::microseconds(1)))
42 } else {
43 day_start(zone, date)
44 };
45 bound.ok_or_else(|| format!("date '{s}' is out of range"))
46}
47
48pub fn parse_day(s: &str) -> Result<NaiveDate, String> {
50 let s = s.trim();
51 NaiveDate::parse_from_str(s, DATE_FORMAT)
52 .map_err(|_| format!("'{s}' is not a day, expected YYYY-MM-DD"))
53}
54
55pub fn parse_post_date(s: &str) -> Result<DateTime<Utc>, String> {
58 let s = s.trim();
59 match NaiveDate::parse_from_str(s, DATE_FORMAT) {
60 Ok(date) => date
61 .and_hms_opt(12, 0, 0)
62 .map(|noon| noon.and_utc())
63 .ok_or_else(|| format!("date '{s}' is out of range")),
64 Err(_) => parse_date(s, false),
65 }
66}
67
68fn day_start<Z: TimeZone>(zone: &Z, date: NaiveDate) -> Option<DateTime<Utc>> {
71 let midnight = date.and_time(NaiveTime::MIN);
72 if let Some(start) = zone.from_local_datetime(&midnight).earliest() {
73 return Some(start.with_timezone(&Utc));
74 }
75 let reached = |seconds: i64| {
76 DateTime::from_timestamp(seconds, 0)
77 .is_some_and(|at| zone.from_utc_datetime(&at.naive_utc()).naive_local() >= midnight)
78 };
79 let around = Duration::hours(26).num_seconds();
81 let mut before = midnight.and_utc().timestamp() - around;
82 let mut after = midnight.and_utc().timestamp() + around;
83 while after - before > 1 {
84 let middle = before + (after - before) / 2;
85 if reached(middle) {
86 after = middle;
87 } else {
88 before = middle;
89 }
90 }
91 DateTime::from_timestamp(after, 0)
92}
93
94#[must_use]
96pub fn now_instant() -> String {
97 Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true)
98}
99
100#[must_use]
105pub fn step_date(s: &str, delta_days: i64) -> Option<String> {
106 let s = s.trim();
107 let delta = Duration::try_days(delta_days)?;
108 if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
109 let stepped = dt.checked_add_signed(delta)?;
110 return Some(stepped.to_rfc3339_opts(SecondsFormat::AutoSi, true));
111 }
112 if let Ok(date) = NaiveDate::parse_from_str(s, DATE_FORMAT) {
113 return Some(
114 date.checked_add_signed(delta)?
115 .format(DATE_FORMAT)
116 .to_string(),
117 );
118 }
119 let stepped = parse_date(s, false).ok()?.checked_add_signed(delta)?;
120 let output = if NaiveDateTime::parse_from_str(s, SECOND_OUTPUT).is_ok() {
121 SECOND_OUTPUT
122 } else {
123 MINUTE_OUTPUT
124 };
125 Some(stepped.format(output).to_string())
126}