Home > database >  How to always show milliseconds when parsing datetime with chrono in rust?
How to always show milliseconds when parsing datetime with chrono in rust?

Time:12-01

I am trying to format a chrono::NaiveDate like this: %Y-%m-%dT%H:%M:%S%.f

According to the third example in the documentation I expected this to work like so:

use chrono::NaiveDate;

fn main() {
    let date = NaiveDate::from_ymd(2015, 7, 1).and_hms_milli(0, 0, 0, 0);
    println!("{}", date.format("%Y-%m-%dT%H:%M:%S%.f"));
}

However instead of the desired output 2015-07-01T00:00:00.000 this prints 2015-07-01T00:00:00.

Rust Playground is here

Apparently the milliseconds only get included, if they are not zero:

use chrono::NaiveDate;

fn main() {
    let date = NaiveDate::from_ymd(2015, 7, 1).and_hms_milli(0, 0, 0, 1);
    println!("{}", date.format("%Y-%m-%dT%H:%M:%S%.f"));
}

is there an option to always include them?

CodePudding user response:

You can use .3f as the last specifier. This is similar to .%f but left-aligned but fixed to a length of 3

println!("{}", date.format("%Y-%m-%dT%H:%M:%S%.3f"));
  • Related