Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 433
Mathe Eliel Avatar asked Sep 30 '20 22:09

Mathe Eliel


People also ask

How do I convert DateTime to ISO 8601?

toISOString() method is used to convert the given date object's contents into a string in ISO format (ISO 8601) i.e, in the form of (YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss.

How do I write ISO 8601?

ISO 8601 FormatsISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).

What time zone is ISO 8601?

Universal Coordinate Time is the time at the zero meridian, near Greenwich, England. UTC is a datetime value that uses the ISO 8601 basic form yyyymmddT hhmmss+|– hhmm or the ISO 8601 extended form yyyy-mm-ddT hh:mm:ss+|– hh:mm.

How do you get a timestamp in Rust?

In Rust we have time::get_time() which returns a Timespec with the current time as seconds and the offset in nanoseconds since midnight, January 1, 1970.


1 Answers

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.

like image 92
NovaDenizen Avatar answered Oct 07 '22 11:10

NovaDenizen