How to convert Instant time to String?

Viewed 701

I'm trying to parse a std::time::Instant into a String, but I don't know how to do it properly.

use std::{time::Instant};

// let my_str: String = Instant::now();

The Instant struct doesn't seem to have a parse or to_string method.

I want to get the current timestamp, could be in any format, and store it in a struct/database as a String.

1 Answers

As the documentation of std::time::Instant mentions:

Instants are opaque types that can only be compared to one another.

For a more complete time library, which supports time zones and printing, use chrono, whose documentation has a whole section about formatting time.

If you want to store the time in a database, then you are most likely interested in the to_rfc3339 method which serializes time as per ISO 8601/RFC3339:

use chrono::Utc;

fn main() {
    let time = Utc::now();

    println!("{}", time.to_rfc3339());
}

prints 2022-02-26T16:17:33.088851150+00:00.

Related