Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Rust DateTime Formatting Examples With chrono

Just a few date formats I like to use

Code

//! ```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![
    ("", "%Y-%m-%d %H:%M:%S"),
    ("", "%Y-%m-%dT%H:%M:%S"),
    ("", "%B %Y"),
    ("", "%b %Y"),
  ];
  formats.iter().for_each(|format| 
    {
      println!("{}", format!("{:^24} | {:^25}", format.1, dt.format(format.1)));
    }
  );
}

Results

%Y-%m-%d %H:%M:%S     |    2003-01-08 04:05:06   
   %Y-%m-%dT%H:%M:%S     |    2003-01-08T04:05:06   
         %B %Y           |       January 2003       
         %b %Y           |         Jan 2003