| 1 | # runtime-format |
| 2 | |
| 3 | Formatting, but processed at runtime. |
| 4 | |
| 5 | ```rust |
| 6 | use runtime_format::{FormatArgs, FormatKey, FormatKeyError}; |
| 7 | use core::fmt; |
| 8 | |
| 9 | impl FormatKey for DateTime { |
| 10 | fn fmt(&self, key: &str, f: &mut fmt::Formatter<'_>) -> Result<(), FormatKeyError> { |
| 11 | use core::fmt::Write; |
| 12 | match key { |
| 13 | "year" => write!(f, "{}", self.year()).map_err(FormatKeyError::Fmt), |
| 14 | "month" => write!(f, "{}", self.short_month_name()).map_err(FormatKeyError::Fmt), |
| 15 | "day" => write!(f, "{}", self.day()).map_err(FormatKeyError::Fmt), |
| 16 | "hours" => write!(f, "{}", self.hours()).map_err(FormatKeyError::Fmt), |
| 17 | "minutes" => write!(f, "{}", self.minutes()).map_err(FormatKeyError::Fmt), |
| 18 | "seconds" => write!(f, "{}", self.seconds()).map_err(FormatKeyError::Fmt), |
| 19 | _ => Err(FormatKeyError::UnknownKey), |
| 20 | } |
| 21 | } |
| 22 | } |
| 23 | let now = DateTime::now(); |
| 24 | let fmt = "{month} {day} {year} {hours}:{minutes}:{seconds}"; |
| 25 | let args = FormatArgs::new(fmt, &now); |
| 26 | |
| 27 | // Outputs "Jan 25 2023 16:27:53" |
| 28 | println!("{args}"); |
| 29 | ``` |