Search code examples
rustdatetime-formatiso8601

How do I convert a SystemTime to ISO 8601 in Rust?


I have a SystemTime variable and I want to get the ISO 8601 format from that date.


Solution

  • The chrono package is the right tool for the job here. SystemTime may or may not be UTC, and chrono takes care of many irritating little details.

    use chrono::prelude::{DateTime, Utc};
    
    fn iso8601(st: &std::time::SystemTime) -> String {
        let dt: DateTime<Utc> = st.clone().into();
        format!("{}", dt.format("%+"))
        // formats like "2001-07-08T00:34:60.026490+09:30"
    }
    

    To customize the format differently, see the chrono::format::strftime docs.