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 Format With Abbreviated Months In chrono

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();
  println!("{}", abbreviated_month_string(dt));

  let date_string = "2003-05-08 04:05:06";
  let dt = NaiveDateTime::parse_from_str(date_string, "%Y-%m-%d %H:%M:%S").unwrap();
  println!("{}", abbreviated_month_string(dt));
}

fn abbreviated_month_string(dt: NaiveDateTime) -> String {
  match dt.format("%b").to_string().as_ref() {
    "May" => dt.format("%b %Y").to_string(),
    _ => dt.format("%b. %Y").to_string()
  }
}

Results

Jan. 2003
May 2003