shared/
time.rs

1pub fn unix_to_human_time(unix_timestamp: i64) -> (u16, u8, u8, u8, u8, u8) {
2    // Constants for calculations
3    const SECONDS_IN_MINUTE: i64 = 60;
4    const SECONDS_IN_HOUR: i64 = 60 * SECONDS_IN_MINUTE;
5    const SECONDS_IN_DAY: i64 = 24 * SECONDS_IN_HOUR;
6    const DAYS_IN_YEAR: i64 = 365;
7    const DAYS_IN_LEAP_YEAR: i64 = 366;
8
9    // Start from 1970
10    let mut year = 1970;
11    let mut days_since_epoch = unix_timestamp / SECONDS_IN_DAY;
12    let mut remaining_seconds = unix_timestamp % SECONDS_IN_DAY;
13
14    if remaining_seconds < 0 {
15        // Handle negative Unix timestamps
16        days_since_epoch -= 1;
17        remaining_seconds += SECONDS_IN_DAY;
18    }
19
20    // Determine the current year
21    while days_since_epoch
22        >= if is_leap_year(year) {
23            DAYS_IN_LEAP_YEAR
24        } else {
25            DAYS_IN_YEAR
26        }
27    {
28        days_since_epoch -= if is_leap_year(year) {
29            DAYS_IN_LEAP_YEAR
30        } else {
31            DAYS_IN_YEAR
32        };
33        year += 1;
34    }
35
36    // Determine the current month and day
37    let mut month = 0;
38    while days_since_epoch >= days_in_month(year, month) {
39        days_since_epoch -= days_in_month(year, month);
40        month += 1;
41    }
42
43    // Remaining days are the day of the month
44    let day = days_since_epoch + 1;
45
46    // Calculate hour, minute, and second from remaining seconds
47    let hour = remaining_seconds / SECONDS_IN_HOUR;
48    remaining_seconds %= SECONDS_IN_HOUR;
49    let minute = remaining_seconds / SECONDS_IN_MINUTE;
50    let second = remaining_seconds % SECONDS_IN_MINUTE;
51
52    (
53        year as u16,
54        month as u8 + 1,
55        day as u8,
56        hour as u8,
57        minute as u8,
58        second as u8,
59    )
60}
61
62pub fn is_leap_year(year: i64) -> bool {
63    (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
64}
65
66pub fn days_in_month(year: i64, month: usize) -> i64 {
67    // Number of days in each month (non-leap year)
68    const DAYS_IN_MONTH: [i64; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
69
70    if month == 1 && is_leap_year(year) {
71        // February in a leap year
72        29
73    } else {
74        DAYS_IN_MONTH[month]
75    }
76}