hyperlane_time/time/
time.rs1use super::r#type::from_env_var;
2use std::fmt::Write;
3use std::time::{Duration, SystemTime, UNIX_EPOCH};
4
5static LEAP_YEAR: [u64; 12] = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
7static COMMON_YEAR: [u64; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
9
10#[inline]
18fn is_leap_year(year: u64) -> bool {
19 (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
20}
21
22#[inline]
31fn calculate_current_date() -> (u64, u64, u64, u64) {
32 let start: SystemTime = SystemTime::now();
34 let duration: Duration = start.duration_since(UNIX_EPOCH).unwrap();
35 let total_seconds: u64 = duration.as_secs();
36 let mut total_days: u64 = total_seconds / 86400;
37 let mut year: u64 = 1970;
38 while total_days >= if is_leap_year(year) { 366 } else { 365 } {
39 total_days -= if is_leap_year(year) { 366 } else { 365 };
40 year += 1;
41 }
42 let mut month: u64 = 1;
43 let month_days: [u64; 12] = if is_leap_year(year) {
44 LEAP_YEAR
45 } else {
46 COMMON_YEAR
47 };
48 while total_days >= month_days[month as usize - 1] {
49 total_days -= month_days[month as usize - 1];
50 month += 1;
51 }
52 let day: u64 = total_days + 1;
53 let remaining_seconds: u64 = total_seconds % 86400;
54 (year, month, day, remaining_seconds)
55}
56
57#[inline]
62pub fn current_time() -> String {
63 let (year, month, day, remaining_seconds) = calculate_current_date();
64 let timezone_offset: u64 = from_env_var().value(); let hours: u64 = ((remaining_seconds + timezone_offset) / 3600) % 24;
66 let minutes: u64 = (remaining_seconds % 3600) / 60;
67 let seconds: u64 = remaining_seconds % 60;
68 let mut date_time: String = String::new();
69 write!(
70 &mut date_time,
71 "{:04}-{:02}-{:02} {:02}:{:02}:{:02}",
72 year, month, day, hours, minutes, seconds
73 )
74 .unwrap_or_default();
75 date_time
76}
77
78#[inline]
83pub fn current_date() -> String {
84 let (year, month, day, _) = calculate_current_date();
85 let mut date_time: String = String::new();
86 write!(&mut date_time, "{:04}-{:02}-{:02}", year, month, day).unwrap_or_default();
87 date_time
88}