Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Date Time Formatting In Rust With Chrono

rust
//! ```cargo
//! [dependencies]
//! chrono = "0.4.31"
//! ```

use chrono::prelude::*;

fn main() {
  let date_string = "2003-01-08 04:05:06";
  let dt = NaiveDateTime::parse_from_str(date_string, "%Y-%m-%d %H:%M:%S").unwrap();
  let formats: Vec<(&str, &str)>= vec![
    ("Year (without century, zero padded)", "%y"),
    ("Year (without century, no padding)", "%-y"),
    ("Year (with centry)", "%Y"),
    ("Month (zero padded)", "%m"),
    ("Month (no padding)", "%-m"),
    ("Month Name (full)", "%B"),
    ("Month Name (abbrevaited)", "%b"),
    ("Day of Month (zero padded)", "%d"),
    ("Day of Month (no padding)", "%-d"),
    ("Day of Week Name (full)", "%A"), 
    ("Day of Week Name (abbreviated)", "%a"), 
    ("Day of Week Zero Index Number", "%w"), 
    ("Day of Year (zero padded)", "%j"),
    ("Day of Year (no padding)", "%-j"),
    ("Hour (24hr clock, zero padded)", "%H"),
    ("Hour (24hr clock, no padding)", "%-H"),
    ("Hour (12hr clock, zero padded)", "%I"),
    ("Hour (12hr clock, no padding)", "%-I"),
    ("Minute (zero padded)", "%M"),
    ("Minute (no padding)", "%-M"),
    ("Second (zero padded)", "%S"),
    ("Second (no padding)", "%-S"),
    ("Microsecond (zero padded)", "%f"),
    ("Week number (Sunday based)", "%U"),
    ("Week number (Monday based)", "%W"),
    ("AM/PM", "%p"),
    ("Locale DateTime String", "%c"),
    ("Locale Date String", "%x"),
    ("Locale Time String", "%X"),
    ("Literal %", "%%"),
  ];
  formats.iter().for_each(|format| 
    {
      println!("{}", format!("{:^4} {:<36} | {:^25}", format.1, format.0, dt.format(format.1)));
      println!("");
    }
  );
}
results start