Skip to main content

forms/
date.rs

1//! The one date parser and the date helpers of the clients.
2
3use 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
12/// [`parse_date_in`] for UTC.
13pub fn parse_date(s: &str, range_end: bool) -> Result<DateTime<Utc>, String> {
14    parse_date_in(s, range_end, &Utc)
15}
16
17/// Parse RFC3339 (full precision), `YYYY-MM-DD`, `YYYY-MM-DDTHH:MM[:SS]` or
18/// `YYYY-MM-DD HH:MM` (offset-free forms are UTC). A date-only value is the start of
19/// that day in `zone`, or, when `range_end` is set, the last microsecond (the finest
20/// instant Postgres stores) before the next local day starts.
21pub 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
48/// A calendar day `YYYY-MM-DD`; a value with a time is refused, never truncated.
49pub 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
55/// [`parse_date`] for a transaction post date: a date-only value is noon UTC, so it
56/// stays on that day for every zone from UTC-12 to UTC+11.
57pub 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
68/// The first instant on or after local midnight of `date`: the earlier of a repeated
69/// midnight, and the end of the gap when midnight or the whole day is skipped.
70fn 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    // The largest UTC offset magnitude is 14h; 26h leaves a margin for a skipped day.
80    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/// The current instant as a full RFC3339 UTC value, the seed of an empty date.
95#[must_use]
96pub fn now_instant() -> String {
97    Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true)
98}
99
100/// Add `delta_days` to the date in `s`. An RFC3339 value keeps its offset,
101/// seconds and fractions; `YYYY-MM-DDTHH:MM:SS` keeps its seconds; a date-only value stays
102/// date-only; other forms step to `YYYY-MM-DDTHH:MM`. `None`
103/// leaves the caller's buffer untouched (unparseable input or overflow).
104#[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}