Ben Chuanlong Du's Blog

It is never too late to learn.

Date and Time in Rust

In [ ]:
:timing
:sccache 1

Comments

  1. There are a few 3rd-party Rust crates time, quanta and chrono for handling time/date. The Rust crate time, is recommended. For detailed discussions, please refer to No Time for Chrono .
In [5]:
use std::time::{SystemTime, UNIX_EPOCH};
In [6]:
SystemTime::now()
Out[6]:
SystemTime { tv_sec: 1638324570, tv_nsec: 811168245 }
In [7]:
let start = SystemTime::now();
start.duration_since(UNIX_EPOCH).expect("Time went backwards")
Out[7]:
1638324597.690945736s
In [8]:
let start = SystemTime::now();
start.duration_since(UNIX_EPOCH).unwrap()
Out[8]:
1638324623.948540298s
In [10]:
let start = SystemTime::now();
start.duration_since(UNIX_EPOCH).unwrap().as_secs()
Out[10]:
1638324793
In [9]:
let start = SystemTime::now();
start.duration_since(UNIX_EPOCH).unwrap().as_millis()
Out[9]:
1638324649987
In [15]:
let start = SystemTime::now();
start.duration_since(UNIX_EPOCH).unwrap().as_nanos()
Out[15]:
1638325403263831531

Format SystemTime (as String)

SystemTime itself does not support formatting as string. However, it can be done indirectly by casting SystemTime to chrono::Datetime first.

In [11]:
:dep chrono = "0.4.19"
In [12]:
use std::time::SystemTime;
use chrono::offset::Local;
use chrono::DateTime;
In [13]:
let datetime: DateTime<Local> = SystemTime::now().into();
println!("{}", datetime.format("%Y-%m-%d %H:%M:%S.%f"));
2021-11-30 18:15:06.485079503
In [14]:
Local::now()
Out[14]:
2021-11-30T18:15:12.199268942-08:00

The Rust Crate time

In [ ]:

In [ ]:

Comments