It seems there is no way I can turn SystemTime into a string. I have to use SystemTime because I need the value returned from std::fs::Metadata::created().
16
votes
2 Answers
22
votes
You should use Chrono for its formatting support. Since Chrono v0.4.0 this is much easier, as it now implements direct conversions from std::time::SystemTime:
extern crate chrono;
use chrono::offset::Utc;
use chrono::DateTime;
use std::time::SystemTime;
let system_time = SystemTime::now();
let datetime: DateTime<Utc> = system_time.into();
println!("{}", datetime.format("%d/%m/%Y %T"));
If you wanted the time in local timezone instead of UTC, use Local instead of Utc.
For the full list of formatting specifiers see the Chrono documentation.
1
votes
The time crate is now a viable alternative to chrono. See the format() method for details on returning a String from an OffsetDateTIme. Also make sure to check the strftime specifiers table when making your formatting string.
use time::OffsetDateTime;
use std::time::SystemTime;
fn systemtime_strftime<T>(dt: T, format: &str) -> String
where T: Into<OffsetDateTime>
{
dt.into().format(format)
}
fn main() {
let st = SystemTime::now();
println!("{}", systemtime_strftime(st, "%d/%m/%Y %T"));
}