2024-09-19 19:26:57 +00:00
|
|
|
use chrono::prelude::*;
|
2024-07-01 15:56:10 +00:00
|
|
|
use std::time::{SystemTime, UNIX_EPOCH};
|
|
|
|
|
|
|
|
/// Get the current time since epoch
|
2024-07-02 20:55:51 +00:00
|
|
|
pub fn time_secs() -> u64 {
|
|
|
|
SystemTime::now()
|
|
|
|
.duration_since(UNIX_EPOCH)
|
|
|
|
.unwrap()
|
|
|
|
.as_secs()
|
|
|
|
}
|
2024-07-01 15:56:10 +00:00
|
|
|
|
2024-07-02 20:55:51 +00:00
|
|
|
/// Get the current time since epoch
|
2024-07-01 15:56:10 +00:00
|
|
|
pub fn time_millis() -> u128 {
|
|
|
|
SystemTime::now()
|
|
|
|
.duration_since(UNIX_EPOCH)
|
|
|
|
.unwrap()
|
|
|
|
.as_millis()
|
|
|
|
}
|
2024-09-17 20:31:51 +00:00
|
|
|
|
2024-09-19 19:26:57 +00:00
|
|
|
/// Get the number of the day since 01-01-1970 of a given UNIX timestamp (UTC)
|
2024-09-17 20:31:51 +00:00
|
|
|
pub fn day_number(time: u64) -> u64 {
|
|
|
|
time / (3600 * 24)
|
|
|
|
}
|
|
|
|
|
2024-09-19 19:26:57 +00:00
|
|
|
/// 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)
|
|
|
|
}
|
|
|
|
|
2024-09-17 20:31:51 +00:00
|
|
|
#[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);
|
|
|
|
}
|
|
|
|
}
|