1use chrono::{DateTime, Duration, FixedOffset, Local, NaiveDateTime, ParseError, TimeZone, Utc};
3use std::cmp::Ordering;
4use std::time::{SystemTime, UNIX_EPOCH};
5
6pub struct DateUtil;
7
8impl DateUtil {
9 pub fn current_date_string() -> String {
12 let now = Local::now();
13 now.format("%Y-%m-%d").to_string()
14 }
15
16 pub fn today_string() -> String {
23 let now = Local::now();
24 now.format("%Y-%m-%d").to_string()
25 }
26
27 pub fn yesterday_string() -> String {
42 let now = Local::now();
44 let yesterday = now - Duration::days(1);
46 yesterday.format("%Y-%m-%d").to_string()
48 }
49
50 pub fn tomorrow_string() -> String {
57 let now = Local::now();
59 let tomorrow = now + Duration::days(1);
61 tomorrow.format("%Y-%m-%d").to_string()
63 }
64
65 pub fn cmp_string(time1: &str, time2: &str, fmt: &str) -> Result<Ordering, ParseError> {
83 let naive1 = NaiveDateTime::parse_from_str(time1, fmt)?;
85 let naive2 = NaiveDateTime::parse_from_str(time2, fmt)?;
86 let datetime1: DateTime<Utc> = Utc.from_utc_datetime(&naive1);
87 let datetime2: DateTime<Utc> = Utc.from_utc_datetime(&naive2);
88 let c = datetime1.cmp(&datetime2);
89 Ok(c)
90 }
91
92 pub fn current_time_string() -> String {
95 let now = Local::now();
96 now.format("%Y-%m-%d %H:%M:%S").to_string()
97 }
98
99 pub fn parse_datetime(time: &str) -> Result<DateTime<FixedOffset>, chrono::ParseError> {
102 DateTime::parse_from_str(&format!("{} +0000", time), "%Y-%m-%d %H:%M:%S %z")
103 }
104 pub fn current_timestamp() -> u64 {
106 let time = Local::now();
107 DateUtil::timestamp(time)
108 }
109
110 pub fn timestamp(time: DateTime<Local>) -> u64 {
112 let system_time: SystemTime = time.into();
113 let duration = system_time.duration_since(UNIX_EPOCH).unwrap();
114 let timestamp = duration.as_secs();
115 timestamp
116 }
117
118 pub fn timestamp_add(time: DateTime<Local>, seconds: i64) -> u64 {
120 let diff = Duration::seconds(seconds);
121 let time = time + diff;
122 DateUtil::timestamp(time)
123 }
124}
125
126#[cfg(test)]
127mod tests {
128
129 use super::*;
130
131 #[test]
132 fn test_current_time_string() {
133 let timestring = DateUtil::current_time_string();
134 println!("timestring = {}", timestring);
135 }
136
137 #[test]
138 fn test_current_timestamp() {
139 let ts = DateUtil::current_timestamp();
140 println!("ts = {}", ts);
141 }
142
143 #[test]
144 fn test_parse_datetime() {
145 let x = DateUtil::parse_datetime("2025-08-30 12:00:00");
146 println!("{:?}", x);
147 }
148
149 #[test]
150 fn test_cmp_string() {
151 let c = DateUtil::cmp_string(
152 "2025-08-30 13:00:00",
153 "2025-08-30 12:00:01",
154 "%Y-%m-%d %H:%M:%S",
155 );
156 println!("{:?}", c);
157 }
158}