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