Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format SystemTime to string?

Tags:

time

rust

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

like image 485
PENGUINLIONG Avatar asked Jul 29 '17 07:07

PENGUINLIONG


People also ask

How do I get system time in a string?

You can easily create a String of your current system time using: Date currentDate = new Date(System. currentTimeMillis()); String dateAsString = currentDate. toString();

What is FFF in date format?

The "fff" custom format specifier represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value.


2 Answers

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.

like image 103
Peter Hall Avatar answered Oct 16 '22 11:10

Peter Hall


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

like image 37
YenForYang Avatar answered Oct 16 '22 13:10

YenForYang