use chrono::DateTime; use std::time::{Duration, SystemTime, UNIX_EPOCH}; /// Get the current time since epoch pub fn time() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs() } /// Format unix timestamp to a human-readable string pub fn fmt_time(timestamp: u64) -> String { // Create a DateTime from the timestamp let datetime = DateTime::from_timestamp(timestamp as i64, 0).expect("Failed to parse timestamp!"); // Format the datetime how you want datetime.format("%Y-%m-%d %H:%M:%S").to_string() } /// Convert UNIX time to system time pub fn unix_to_system_time(time: u64) -> SystemTime { UNIX_EPOCH + Duration::from_secs(time) } /// Format UNIX time to HTTP date pub fn unix_to_http_date(time: u64) -> String { httpdate::fmt_http_date(unix_to_system_time(time)) } /// Get build time in UNIX format pub fn build_time() -> u64 { let build_time = build_time::build_time_local!(); let date = chrono::DateTime::parse_from_rfc3339(build_time).expect("Failed to parse compile date"); date.timestamp() as u64 } #[cfg(test)] mod test { use crate::utils::time_utils::{fmt_time, time}; #[test] fn test_time() { assert!(time() > 10); } #[test] fn test_fmt_time() { assert_eq!(fmt_time(1693475465), "2023-08-31 09:51:05"); } }