Skip to content

Instantly share code, notes, and snippets.

@silmeth
Created February 15, 2026 16:00
Show Gist options
  • Select an option

  • Save silmeth/f5e4cedfbecb6f5b08ce4a2a24f45a5c to your computer and use it in GitHub Desktop.

Select an option

Save silmeth/f5e4cedfbecb6f5b08ce4a2a24f45a5c to your computer and use it in GitHub Desktop.
macro to optimize chrono DateTime formatting by lazilly parsing format string and memoization/interning of the result
use std::sync::OnceLock;
use chrono::{DateTime, Utc, format::StrftimeItems};
pub fn format_date(ts: DateTime<Utc>) -> String {
static FORMAT: OnceLock<Vec<chrono::format::Item<'static>>> = OnceLock::new();
let items = FORMAT.get_or_init(|| StrftimeItems::new("%Y-%m-%d").collect());
ts.format_with_items(items.iter()).to_string()
}
/// Creates functions like the one above
macro_rules! def_time_formatting_func {
($name:ident, $format_str:expr) => {
pub fn $name(ts: chrono::DateTime<chrono::Utc>) -> String {
static FORMAT: std::sync::OnceLock<Vec<chrono::format::Item<'static>>> = std::sync::OnceLock::new();
let items = FORMAT.get_or_init(|| chrono::format::StrftimeItems::new($format_str).collect());
ts.format_with_items(items.iter()).to_string()
}
};
}
def_time_formatting_func!(format_iso, "%Y-%m-%dT%H:%M:%S%z");
def_time_formatting_func!(format_pretty, "%Y-%m-%d %_H:%M");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment