diary/utils/
date.rs

1use std::str::FromStr;
2
3use chrono::{DateTime, Local, NaiveDate, ParseError, TimeZone};
4use clap::ArgMatches;
5
6pub const fn date_superscript(day: u32) -> &'static str {
7    let unit = day % 10;
8
9    match unit {
10        1 => "st",
11        2 => "nd",
12        3 => "rd",
13        _ => "th",
14    }
15}
16
17pub fn parse_date_option(args: &ArgMatches) -> Result<DateTime<Local>, ParseError> {
18    Ok(match args.get_one::<String>("date") {
19        Some(val) => {
20            let date = NaiveDate::from_str(val)?.and_hms_opt(0, 0, 0).unwrap();
21            Local.from_utc_datetime(&date)
22        }
23        _ => Local::now(),
24    })
25}
26
27#[cfg(test)]
28mod tests {
29    use super::date_superscript;
30    #[test]
31    fn date_superscript_st() {
32        assert_eq!("st", date_superscript(21));
33    }
34    #[test]
35    fn date_superscript_nd() {
36        assert_eq!("nd", date_superscript(12));
37    }
38    #[test]
39    fn date_superscript_rd() {
40        assert_eq!("rd", date_superscript(23));
41    }
42    #[test]
43    fn date_superscript_th() {
44        assert_eq!("th", date_superscript(17));
45    }
46}