dev_tool/
date_util.rs

1// 日期工具
2use chrono::{DateTime, Duration, FixedOffset, Local, TimeZone, Utc};
3use std::time::{SystemTime, UNIX_EPOCH};
4
5pub struct DateUtil;
6
7impl DateUtil {
8    /// 获取当前日期字符串,输出格式:%Y-%m-%d
9    ///
10    pub fn current_date_string() -> String {
11        let now = Local::now();
12        now.format("%Y-%m-%d").to_string()
13    }
14
15    /// 获取当前时间字符串,输出格式:%Y-%m-%d %H:%M:%S
16    ///
17    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    /// # 参数
23    /// - time: 格式如:"2025-08-30 12:00:00"
24    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    /// 当前时间戳(秒),返回10位长度
28    pub fn current_timestamp() -> u64 {
29        let time = Local::now();
30        DateUtil::timestamp(time)
31    }
32
33    /// 返回10位时间戳(秒)
34    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    /// 时间戳加减法(秒)
42    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}