56 lines
1.3 KiB
Rust
56 lines
1.3 KiB
Rust
use chrono::prelude::*;
|
|
use std::time::{SystemTime, UNIX_EPOCH};
|
|
|
|
/// Get the current time since epoch
|
|
pub fn time_secs() -> u64 {
|
|
SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.unwrap()
|
|
.as_secs()
|
|
}
|
|
|
|
/// Get the current time since epoch
|
|
pub fn time_millis() -> u128 {
|
|
SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.unwrap()
|
|
.as_millis()
|
|
}
|
|
|
|
/// Get the number of the day since 01-01-1970 of a given UNIX timestamp (UTC)
|
|
pub fn day_number(time: u64) -> u64 {
|
|
time / (3600 * 24)
|
|
}
|
|
|
|
/// Get current day number
|
|
pub fn curr_day_number() -> u64 {
|
|
day_number(time_secs())
|
|
}
|
|
|
|
/// Get current hour, 00 => 23 (local time)
|
|
pub fn curr_hour() -> u32 {
|
|
let local: DateTime<Local> = Local::now();
|
|
local.hour()
|
|
}
|
|
|
|
/// Get the first second of the day (local time)
|
|
pub fn time_start_of_day() -> anyhow::Result<u64> {
|
|
let local: DateTime<Local> = Local::now()
|
|
.with_time(NaiveTime::from_hms_opt(0, 0, 0).unwrap())
|
|
.unwrap();
|
|
Ok(local.timestamp() as u64)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod test {
|
|
use crate::utils::time_utils::day_number;
|
|
|
|
#[test]
|
|
fn test_time_of_day() {
|
|
assert_eq!(day_number(500), 0);
|
|
assert_eq!(day_number(1726592301), 19983);
|
|
assert_eq!(day_number(1726592401), 19983);
|
|
assert_eq!(day_number(1726498701), 19982);
|
|
}
|
|
}
|