format a date in to the format month day, year hour:minute:second.fff am/pm in rust

To format a date in the format "month day, year hour:minute:second.fff am/pm" in Rust, you can use the chrono crate, which provides a way to work with date and time values.

First, you need to create a DateTime value using the chrono::DateTime::parse_from_str method, passing in a string representing your date/time value and a format string that matches the input string.

main.rs
use chrono::{DateTime, Local, NaiveDateTime, TimeZone};

let input_date_str = "2021-11-29 13:45:00.000";
let input_date_format = "%Y-%m-%d %H:%M:%S%.3f";
let local: DateTime<Local> = DateTime::parse_from_str(input_date_str, input_date_format)?
    .with_timezone(&Local);
272 chars
7 lines

Next, you can use the format method to format the date in the desired output format.

main.rs
let output_date_format = "%B %e, %Y %I:%M:%S%.3f %p";
let formatted_date = local.format(output_date_format);

println!("{}", formatted_date);
142 chars
5 lines

This will output the formatted date string "November 29, 2021 01:45:00.000 PM".

gistlibby LogSnag