dev_tool/
date_util.rs

1
2use chrono::{DateTime, Duration, FixedOffset, Local, NaiveDateTime, ParseError, TimeZone, Utc};
3use std::cmp::Ordering;
4use std::time::{SystemTime, UNIX_EPOCH};
5
6/// 日期工具,包含常用快捷生成,如获取当日时间字符串、格式化、时间字符串解析等
7pub struct DateUtil;
8
9impl DateUtil {
10    /// 获取当前日期字符串,输出格式:%Y-%m-%d
11    ///
12    pub fn current_date_string() -> String {
13        let now = Local::now();
14        now.format("%Y-%m-%d").to_string()
15    }
16
17    /// 获取当前日期的字符串表示
18    ///
19    /// 该函数获取本地当前时间,并将其格式化为"年-月-日"的字符串格式。
20    ///
21    /// # 返回值
22    /// 返回格式为"YYYY-MM-DD"的日期字符串
23    pub fn today_string() -> String {
24        let now = Local::now();
25        now.format("%Y-%m-%d").to_string()
26    }
27
28    /// 获取昨天日期的字符串表示
29    ///
30    /// 该函数计算昨天的日期,并将其格式化为"YYYY-MM-DD"格式的字符串。
31    ///
32    /// # Returns
33    ///
34    /// 返回昨天日期的字符串表示,格式为"YYYY-MM-DD"
35    ///
36    /// # Example
37    ///
38    /// ```
39    /// let yesterday = yesterday_string();
40    /// println!("{}", yesterday); // 输出类似 "2023-12-06"
41    /// ```
42    pub fn yesterday_string() -> String {
43        // 获取当前本地时间
44        let now = Local::now();
45        // 计算昨天的时间
46        let yesterday = now - Duration::days(1);
47        // 将昨天的日期格式化为字符串并返回
48        yesterday.format("%Y-%m-%d").to_string()
49    }
50
51    /// 获取明天日期的字符串表示
52    ///
53    /// 该函数计算明天的日期,并将其格式化为"YYYY-MM-DD"格式的字符串。
54    ///
55    /// # 返回值
56    /// 返回表示明天日期的字符串,格式为"YYYY-MM-DD"
57    pub fn tomorrow_string() -> String {
58        // 获取当前本地时间
59        let now = Local::now();
60        // 计算明天的时间
61        let tomorrow = now + Duration::days(1);
62        // 将明天的日期格式化为字符串并返回
63        tomorrow.format("%Y-%m-%d").to_string()
64    }
65
66    /// 比较两个时间字符串的大小
67    ///
68    /// 该函数将两个时间字符串按照指定的格式解析为DateTime对象,然后进行比较。
69    ///
70    /// # 参数
71    /// * `time1` - 第一个时间字符串
72    /// * `time2` - 第二个时间字符串
73    /// * `fmt` - 时间格式字符串,用于解析time1和time2
74    ///
75    /// # 返回值
76    /// * `Ok(Ordering)` - 比较结果,Ordering::Less表示time1小于time2,
77    ///                    Ordering::Equal表示time1等于time2,
78    ///                    Ordering::Greater表示time1大于time2
79    /// * `Err(ParseError)` - 时间解析失败时返回错误信息
80    ///
81    /// # 错误处理
82    /// 如果任一时间字符串无法按照指定格式解析,函数将返回ParseError错误
83    pub fn cmp_string(time1: &str, time2: &str, fmt: &str) -> Result<Ordering, ParseError> {
84        // 将两个时间字符串转换为DateTime对象,然后进行比较大小
85        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    /// 获取当前时间字符串,输出格式:%Y-%m-%d %H:%M:%S
94    ///
95    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    /// # 参数
101    /// - time: 格式如:"2025-08-30 12:00:00"
102    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    /// 当前时间戳(秒),返回10位长度
106    pub fn current_timestamp() -> u64 {
107        let time = Local::now();
108        DateUtil::timestamp(time)
109    }
110
111    /// 返回10位时间戳(秒)
112    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    /// 时间戳加减法(秒)
120    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}