autopush_common/util/
timing.rs

1use chrono::prelude::*;
2
3/// Get the time since the UNIX epoch in seconds
4pub fn sec_since_epoch() -> u64 {
5    Utc::now().timestamp() as u64
6}
7
8/// Get the time since the UNIX epoch in milliseconds
9pub fn ms_since_epoch() -> u64 {
10    Utc::now().timestamp_millis() as u64
11}
12
13/// Return UTC midnight for the current day.
14pub fn ms_utc_midnight() -> u64 {
15    let now = Utc::now();
16    Utc.with_ymd_and_hms(now.year(), now.month(), now.day(), 0, 0, 0)
17        .single()
18        .expect("Clock error") // Something had to go horribly wrong. Panic is ok.
19        .timestamp_millis() as u64
20}
21
22/// Get the time since the UNIX epoch in microseconds
23#[allow(dead_code)]
24pub fn us_since_epoch() -> u64 {
25    Utc::now().timestamp_micros() as u64
26}
27
28/// Display a formatted date-time string from a SystemTime
29///
30/// (This is useful in dev/debugging)
31#[allow(dead_code)]
32pub fn date_string_from_systemtime(ts: std::time::SystemTime) -> String {
33    let dt: chrono::DateTime<chrono::Utc> = ts.into();
34    dt.format("%Y-%m-%d %H:%M:%S.%f").to_string()
35}
36
37/// Display a formatted date-time string from a UTC offset in millis
38///
39/// (This is useful in dev/debugging)
40#[allow(dead_code)]
41pub fn date_string_from_utc_ms(offset: u64) -> String {
42    let utc = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_millis(offset);
43    date_string_from_systemtime(utc)
44}