Thanks for @coffeed-up-hacker's answer.It helps me a lot.
I tried many different ways to do this, and it seems that built-in functions can not format SystemTime to readable time string.
Finally, I found a better way and it applies to a variety of situations:
extern crate chrono;
use chrono::prelude::DateTime;
use chrono::Utc;
use std::time::{SystemTime, UNIX_EPOCH, Duration};
fn main(){
// Creates a new SystemTime from the specified number of whole seconds
let d = UNIX_EPOCH + Duration::from_secs(1524885322);
// Create DateTime from SystemTime
let datetime = DateTime::<Utc>::from(d);
// Formats the combined date and time with the specified format string.
let timestamp_str = datetime.format("%Y-%m-%d %H:%M:%S.%f").to_string();
println!{"{}",timestamp_str};
}
Output:
2018-04-28 03:15:22.000000000
To get local time string, just use this :DateTime::<Local>::from(d)
.
Also, we can use Duration::from_millis
or Duration::from_micros
or Duration::from_nanos
to convert millisecond, microsecond, nanoseconds to readable string.