1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
extern crate chrono;

use chrono::Datelike;
use chrono::NaiveDate;
use chrono::NaiveDateTime;
use chrono::NaiveTime;
use chrono::TimeZone;
use chrono::Timelike;
use chrono::Utc;
use chrono::Weekday;

static CHRONO_TIME_FORMAT: &str = "%H:%M:%S";
static CHRONO_DATE_FORMAT: &str = "%Y-%m-%d";
static CHRONO_DATE_TIME_FORMAT: &str = "%Y-%m-%d %H:%M:%S";
static CHRONO_DATE_TIME_FULL_FORMAT: &str = "%Y-%m-%d %H:%M:%S%.3f";

pub fn get_unix_timestamp_ms() -> i64 {
    Utc::now().timestamp()
}

pub fn time_stamp_to_date(time_stamp: i64) -> String {
    let utc = NaiveDateTime::from_timestamp_opt(time_stamp, 0).unwrap();
    let datetime = Utc.from_utc_datetime(&utc);
    datetime.format(CHRONO_DATE_FORMAT).to_string()
}

pub fn time_stamp_to_time(time_stamp: i64) -> String {
    let utc = NaiveDateTime::from_timestamp_opt(time_stamp, 0).unwrap();
    let datetime = Utc.from_utc_datetime(&utc);
    datetime.format(CHRONO_TIME_FORMAT).to_string()
}

pub fn time_stamp_to_date_time(time_stamp: i64) -> String {
    let utc = NaiveDateTime::from_timestamp_opt(time_stamp, 0).unwrap();
    let datetime = Utc.from_utc_datetime(&utc);
    datetime.format(CHRONO_DATE_TIME_FULL_FORMAT).to_string()
}

pub fn date_to_time_stamp(date: &str) -> i64 {
    let date_time = NaiveDate::parse_from_str(date, CHRONO_DATE_FORMAT).ok();
    if let Some(date) = date_time {
        let zero_time = NaiveTime::from_hms_opt(0, 0, 0).unwrap();
        return date.and_time(zero_time).timestamp();
    }
    0
}

pub fn date_time_to_time_stamp(date: &str) -> i64 {
    let date_time_format = if date.contains('.') {
        CHRONO_DATE_TIME_FULL_FORMAT
    } else {
        CHRONO_DATE_TIME_FORMAT
    };

    let date_time = NaiveDateTime::parse_from_str(date, date_time_format);
    if date_time.is_err() {
        return 0;
    }
    date_time.ok().unwrap().timestamp()
}

pub fn date_time_to_hour(date: i64) -> i64 {
    let date_time = NaiveDateTime::from_timestamp_opt(date, 0);
    let dt = date_time.unwrap().time();
    dt.hour() as i64
}

pub fn date_time_to_minute(date: i64) -> i64 {
    let date_time = NaiveDateTime::from_timestamp_opt(date, 0);
    let dt = date_time.unwrap().time();
    dt.minute() as i64
}

pub fn date_to_day_number_in_week(date: i64) -> u32 {
    let parsed_date = NaiveDateTime::from_timestamp_opt(date, 0).unwrap();
    parsed_date.weekday().number_from_sunday()
}

pub fn date_to_day_number_in_month(date: i64) -> u32 {
    let parsed_date = NaiveDateTime::from_timestamp_opt(date, 0).unwrap();
    parsed_date.day()
}

pub fn date_to_day_number_in_year(date: i64) -> u32 {
    let parsed_date = NaiveDateTime::from_timestamp_opt(date, 0).unwrap();
    parsed_date.ordinal()
}

pub fn date_to_week_number_in_year(date: i64) -> u32 {
    let parsed_date = NaiveDateTime::from_timestamp_opt(date, 0).unwrap();
    let native_date = parsed_date.date();
    let first_day_of_year = NaiveDate::from_ymd_opt(native_date.year(), 1, 1).unwrap();
    let days_diff = native_date
        .signed_duration_since(first_day_of_year)
        .num_days();
    let week_offset = match first_day_of_year.weekday() {
        Weekday::Mon => 0,
        _ => 1,
    };

    let days_with_offset = days_diff + week_offset;
    (days_with_offset / 7) as u32 + 1
}

pub fn date_to_day_name(date: i64) -> String {
    let parsed_date = NaiveDateTime::from_timestamp_opt(date, 0).unwrap();

    let day_name = match parsed_date.weekday() {
        Weekday::Mon => "Monday",
        Weekday::Tue => "Tuesday",
        Weekday::Wed => "Wednesday",
        Weekday::Thu => "Thursday",
        Weekday::Fri => "Friday",
        Weekday::Sat => "Saturday",
        Weekday::Sun => "Sunday",
    };

    day_name.to_string()
}

pub fn date_to_month_name(date: i64) -> String {
    let parsed_date = NaiveDateTime::from_timestamp_opt(date, 0).unwrap();

    let month_name = match parsed_date.month() {
        1 => "January",
        2 => "February",
        3 => "March",
        4 => "April",
        5 => "May",
        6 => "June",
        7 => "July",
        8 => "August",
        9 => "September",
        10 => "October",
        11 => "November",
        12 => "December",
        _ => "",
    };

    month_name.to_string()
}

pub fn date_to_quarter_index(date: i64) -> i64 {
    let parsed_date = NaiveDateTime::from_timestamp_opt(date, 0).unwrap();
    let month = parsed_date.month() as i64;
    (month - 1) / 3 + 1
}

pub fn date_to_year(date: i64) -> i32 {
    let parsed_date = NaiveDateTime::from_timestamp_opt(date, 0).unwrap();
    parsed_date.year()
}

pub fn date_to_month(date: i64) -> u32 {
    let parsed_date = NaiveDateTime::from_timestamp_opt(date, 0).unwrap();
    parsed_date.month()
}

pub fn date_to_weekday(date: i64) -> u32 {
    let parsed_date = NaiveDateTime::from_timestamp_opt(date, 0).unwrap();
    parsed_date.weekday().number_from_monday() - 1
}

pub fn date_to_days_count(date: i64) -> i64 {
    let parsed_date = NaiveDateTime::from_timestamp_opt(date, 0).unwrap();
    let days_since_year_0 = parsed_date.ordinal0() as i64;
    let year = parsed_date.year() as i64;
    let leap_years = (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400;
    let non_leap_years = year - leap_years;
    365 * non_leap_years + 366 * leap_years + days_since_year_0
}

pub fn date_last_day(date: i64) -> i64 {
    let parsed_date = NaiveDateTime::from_timestamp_opt(date, 0).unwrap();
    let (year, month) = (parsed_date.year(), parsed_date.month());

    let curr_month_start = NaiveDate::from_ymd_opt(year, month, 1).unwrap();
    let next_month_start = if month < 12 {
        NaiveDate::from_ymd_opt(year, month + 1, 1)
    } else {
        NaiveDate::from_ymd_opt(year + 1, 1, 1)
    }
    .unwrap();
    let days_in_month = next_month_start - curr_month_start;

    let parsed_date = parsed_date.with_day(1).unwrap();
    let last_day = parsed_date + days_in_month - chrono::Duration::days(1);
    last_day.timestamp()
}

pub fn time_stamp_from_year_and_day(year: i32, day_of_year: u32) -> i64 {
    let date = NaiveDate::from_yo_opt(year, day_of_year).unwrap();
    let datetime = date.and_hms_opt(0, 0, 0).unwrap();
    Utc.from_utc_datetime(&datetime).timestamp()
}

/// Check if String literal is matching SQL time format: HH:MM:SS or HH:MM:SS.SSS
pub fn is_valid_time_format(time_str: &str) -> bool {
    // Check length of the string
    if !(8..=12).contains(&time_str.len()) {
        return false;
    }

    // Split the string into hours, minutes, seconds, and optional milliseconds
    let parts: Vec<&str> = time_str.split(':').collect();
    if parts.len() < 3 || parts.len() > 4 {
        return false;
    }

    // Extract hours, minutes, seconds, and optionally milliseconds
    let hours = parts[0].parse::<u32>().ok();
    let minutes = parts[1].parse::<u32>().ok();
    let seconds_parts: Vec<&str> = parts[2].split('.').collect();
    let seconds = seconds_parts[0].parse::<u32>().ok();
    let milliseconds = if seconds_parts.len() == 2 {
        seconds_parts[1].parse::<u32>().ok()
    } else {
        Some(0)
    };

    // Validate the parsed values
    hours.is_some()
        && minutes.is_some()
        && seconds.is_some()
        && milliseconds.is_some()
        && hours.unwrap() < 24
        && minutes.unwrap() < 60
        && seconds.unwrap() < 60
        && milliseconds.unwrap() < 1000
}

/// Check if String literal is matching SQL Date format: YYYY-MM-DD
pub fn is_valid_date_format(date_str: &str) -> bool {
    // Check length of the string
    if date_str.len() != 10 {
        return false;
    }

    // Split the string into year, month, and day
    let parts: Vec<&str> = date_str.split('-').collect();
    if parts.len() != 3 {
        return false;
    }

    // Extract year, month, and day
    let year = parts[0].parse::<u32>().ok();
    let month = parts[1].parse::<u32>().ok();
    let day = parts[2].parse::<u32>().ok();

    // Validate the parsed values
    year.is_some()
        && month.is_some()
        && day.is_some()
        && year.unwrap() >= 1
        && month.unwrap() >= 1
        && month.unwrap() <= 12
        && day.unwrap() >= 1
        && day.unwrap() <= 31
}

/// Check if String literal is matching SQL Date format: YYYY-MM-DD HH:MM:SS or YYYY-MM-DD HH:MM:SS.SSS
pub fn is_valid_datetime_format(datetime_str: &str) -> bool {
    // Check length of the string
    if !(19..=23).contains(&datetime_str.len()) {
        return false;
    }

    // Split the string into date and time components
    let parts: Vec<&str> = datetime_str.split_whitespace().collect();
    if parts.len() != 2 {
        return false;
    }

    // Check the validity of date and time components
    is_valid_date_format(parts[0]) && is_valid_time_format(parts[1])
}