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