debot_utils/
datetime_utils.rs

1use chrono::{DateTime, Datelike, FixedOffset, Local, Timelike, Utc, Weekday};
2use std::{env, time::SystemTime};
3
4pub struct DateTimeUtils {}
5
6pub trait ToDateTimeString {
7    fn to_datetime_string(self) -> String;
8}
9
10impl ToDateTimeString for i64 {
11    fn to_datetime_string(self) -> String {
12        let datetime = DateTime::<Utc>::from_timestamp(self, 0).expect("Invalid timestamp");
13        datetime.format("%Y-%m-%d %H:%M:%S").to_string()
14    }
15}
16
17impl ToDateTimeString for SystemTime {
18    fn to_datetime_string(self) -> String {
19        let datetime: DateTime<Utc> = self.into();
20        datetime.format("%Y-%m-%d %H:%M:%S").to_string()
21    }
22}
23
24impl DateTimeUtils {
25    pub fn get_current_datetime_string() -> String {
26        let current_time = Utc::now().timestamp();
27        let datetime = DateTime::<Utc>::from_timestamp(current_time, 0).expect("Invalid timestamp");
28        datetime.format("%Y-%m-%d %H:%M:%S").to_string()
29    }
30
31    pub fn get_current_date_string() -> String {
32        let current_time = Utc::now().timestamp();
33        let datetime = DateTime::<Utc>::from_timestamp(current_time, 0).expect("Invalid timestamp");
34        datetime.format("%Y-%m-%d").to_string()
35    }
36}
37
38pub fn get_local_time() -> (i64, String) {
39    let offset_seconds = env::var("TIMEZONE_OFFSET")
40        .unwrap_or_else(|_| "3600".to_string())
41        .parse::<i32>()
42        .expect("Invalid TIMEZONE_OFFSET");
43
44    let offset = FixedOffset::east_opt(offset_seconds).expect("Invalid offset");
45
46    let utc_now: DateTime<Utc> = Utc::now();
47    let local_now = utc_now.with_timezone(&offset);
48    (
49        local_now.timestamp(),
50        local_now.format("%Y-%m-%dT%H:%M:%S%z").to_string(),
51    )
52}
53
54pub fn is_sunday() -> bool {
55    let current_date = Utc::now();
56    current_date.weekday().num_days_from_sunday() == 0
57}
58
59pub fn has_remaining_sunday_hours(threshold: u32) -> bool {
60    if threshold > 24 {
61        panic!("Threshold must be between 0 and 24");
62    }
63
64    let now = Utc::now();
65
66    if now.weekday() != Weekday::Sun {
67        return true;
68    }
69
70    // Calculate the remaining hours in Sunday
71    let remaining_seconds =
72        (23 - now.hour()) * 3600 + (59 - now.minute()) * 60 + (59 - now.second());
73    let remaining_hours = remaining_seconds as f64 / 3600.0;
74
75    // Check if the remaining hours are greater than or equal to the threshold
76    remaining_hours >= threshold as f64
77}
78
79pub fn num_seconds_from_midnight() -> u32 {
80    let now = Local::now().time();
81    now.num_seconds_from_midnight()
82}