loggit/
helper.rs

1use chrono::{self, Datelike, Timelike};
2use std::io::Write;
3use thiserror::Error;
4
5pub(crate) fn get_current_time_in_utc() -> (u32, u32, i32, u32, u32, u32) {
6    let date_time = chrono::Utc::now();
7    let (day, month, year) = (
8        date_time.date_naive().day(),
9        date_time.date_naive().month(),
10        date_time.date_naive().year(),
11    );
12    let (hour, minute, second) = (
13        date_time.time().hour(),
14        date_time.time().minute(),
15        date_time.time().second(),
16    );
17    (day, month, year, hour, minute, second)
18}
19
20pub(crate) fn get_current_date_in_string() -> String {
21    let (day, month, year, _, _, _) = get_current_time_in_utc();
22    format!("{}-{}-{}", day, month, year)
23}
24
25pub(crate) fn get_current_time_in_string() -> String {
26    let (_, _, _, hour, minute, second) = get_current_time_in_utc();
27    format!("{}:{}:{}", hour, minute, second)
28}
29
30pub(crate) fn seconds_to_ymdhms(mut seconds: u64) -> (u64, u64, u64, u64, u64, u64) {
31    const SECONDS_IN_MINUTE: u64 = 60;
32    const SECONDS_IN_HOUR: u64 = 60 * SECONDS_IN_MINUTE;
33    const SECONDS_IN_DAY: u64 = 24 * SECONDS_IN_HOUR;
34
35    let mut year = 1970;
36    let mut month = 1;
37    let mut day = 1;
38
39    let mut days = seconds / SECONDS_IN_DAY;
40    seconds %= SECONDS_IN_DAY;
41
42    let hour = seconds / SECONDS_IN_HOUR;
43    seconds %= SECONDS_IN_HOUR;
44
45    let minute = seconds / SECONDS_IN_MINUTE;
46    let second = seconds % SECONDS_IN_MINUTE;
47
48    let is_leap = |y: u64| -> bool { (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0) };
49
50    let days_in_month = |y: u64, m: u64| -> u64 {
51        match m {
52            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
53            4 | 6 | 9 | 11 => 30,
54            2 => {
55                if is_leap(y) {
56                    29
57                } else {
58                    28
59                }
60            }
61            _ => {
62                eprintln!("Invalid month given");
63                0
64            }
65        }
66    };
67
68    // Calculate the year
69    while days >= if is_leap(year) { 366 } else { 365 } {
70        days -= if is_leap(year) { 366 } else { 365 };
71        year += 1;
72    }
73
74    // Calculate the month
75    while days >= days_in_month(year, month) {
76        days -= days_in_month(year, month);
77        month += 1;
78    }
79
80    day += days; // Remaining days count as the day of the month
81
82    (year, month, day, hour, minute, second)
83}
84
85#[derive(Debug, Error)]
86pub(crate) enum WriteToFileError {
87    #[error("unexpected error")]
88    UnexpectedError(std::io::Error),
89}
90pub(crate) fn write_to_file(file: &mut std::fs::File, text: &str) -> Result<(), WriteToFileError> {
91    writeln!(file, "{}", text).map_err(WriteToFileError::UnexpectedError)
92}