Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to show milliseconds when parsing datetime with chrono in rust?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Rust Playground is here

How can I also include the milliseconds in the output string?

Edit

Apparently the milliseconds 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?

>Solution :

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"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading