Search code examples
datetimerustrfc3339

How can I display chrono DateTime without fractional seconds?


If I print the current time directly, it includes many trailing decimals:

println!("{:?}", chrono::offset::Utc::now());
2022-12-01T07:56:54.242352517Z

How can I get it to print like this?

2022-12-01T07:56:54Z

Solution

  • You can use to_rfc3339_opts. It accepts arguments for the format of the seconds and if the Z should be present.

    let time = chrono::offset::Utc::now();
    let formatted = time.to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
    
    println!("{:?}", time);    // 2022-12-01T08:32:20.580242150Z
    println!("{}", formatted); // 2022-12-01T08:32:20Z
    

    Rust Playground