1use chrono::{DateTime, Duration, FixedOffset, Local, TimeZone, Utc};
3use std::time::{SystemTime, UNIX_EPOCH};
4
5pub struct DateUtil;
6
7impl DateUtil {
8 pub fn current_date_string() -> String {
11 let now = Local::now();
12 now.format("%Y-%m-%d").to_string()
13 }
14
15 pub fn current_time_string() -> String {
18 let now = Local::now();
19 now.format("%Y-%m-%d %H:%M:%S").to_string()
20 }
21
22 pub fn parse_datetime(time: &str) -> Result<DateTime<FixedOffset>, chrono::ParseError> {
25 DateTime::parse_from_str(&format!("{} +0000", time), "%Y-%m-%d %H:%M:%S %z")
26 }
27 pub fn current_timestamp() -> u64 {
29 let time = Local::now();
30 DateUtil::timestamp(time)
31 }
32
33 pub fn timestamp(time: DateTime<Local>) -> u64 {
35 let system_time: SystemTime = time.into();
36 let duration = system_time.duration_since(UNIX_EPOCH).unwrap();
37 let timestamp = duration.as_secs();
38 timestamp
39 }
40
41 pub fn timestamp_add(time: DateTime<Local>, seconds: i64) -> u64 {
43 let diff = Duration::seconds(seconds);
44 let time = time + diff;
45 DateUtil::timestamp(time)
46 }
47}
48
49#[cfg(test)]
50mod tests {
51
52 use super::*;
53
54 #[test]
55 fn test_current_time_string() {
56 let timestring = DateUtil::current_time_string();
57 println!("timestring = {}", timestring);
58 }
59
60 #[test]
61 fn test_current_timestamp() {
62 let ts = DateUtil::current_timestamp();
63 println!("ts = {}", ts);
64 }
65
66 #[test]
67 fn test_parse_datetime() {
68 let x = DateUtil::parse_datetime("2025-08-30 12:00:00");
69 println!("{:?}", x);
70 }
71}