BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / card_date.rs

card_date.rs

card_date.rs 1.4 KiB Download Raw
1use std::fmt::Display;
2use std::sync::LazyLock;
3
4use chrono::{DateTime, Local, TimeZone};
5use regex::{Captures, Regex};
6
7const COMPACT_FORMAT: &str = "%Y-%m-%d";
8const SHORT_FORMAT: &str = "%a, %b %-d, %Y";
9const LONG_FORMAT: &str = "%A, %B %-d, %Y";
10const TIME_FORMAT: &str = "%H:%M";
11
12static DATE_TIME_FUNCTION: LazyLock<Regex> = LazyLock::new(|| {
13 Regex::new(r"(?:\{\{\s*)?\b(DATE|TIME)\(\s*([^,()\s]+)\s*(?:,\s*(SHORT|LONG|COMPACT)\s*)?\)(?:\s*\}\})?")
14 .unwrap()
15});
16
17pub fn format_card_dates(text: &str) -> String {
18 format_card_dates_in(text, &Local)
19}
20
21pub fn format_card_dates_in<Zone>(text: &str, zone: &Zone) -> String
22where
23 Zone: TimeZone,
24 Zone::Offset: Display,
25{
26 DATE_TIME_FUNCTION
27 .replace_all(text, |captures: &Captures| {
28 format_function(captures, zone).unwrap_or_else(|| captures[0].to_owned())
29 })
30 .into_owned()
31}
32
33fn format_function<Zone>(captures: &Captures, zone: &Zone) -> Option<String>
34where
35 Zone: TimeZone,
36 Zone::Offset: Display,
37{
38 let moment = DateTime::parse_from_rfc3339(&captures[2])
39 .ok()?
40 .with_timezone(zone);
41 let pattern = match (&captures[1], captures.get(3).map(|style| style.as_str())) {
42 ("TIME", _) => TIME_FORMAT,
43 (_, Some("SHORT")) => SHORT_FORMAT,
44 (_, Some("LONG")) => LONG_FORMAT,
45 _ => COMPACT_FORMAT,
46 };
47 Some(moment.format(pattern).to_string())
48}