How to format SystemTime to string?

Viewed 11262

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().

2 Answers

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"));
}

Play

Related