Skip to main content

alun_utils/
date.rs

1//! 日期工具:格式化、相对时间、时间戳互转
2
3use chrono::{DateTime, Utc, Local};
4
5/// 日期工具 —— 格式化、相对时间描述、时间戳互转、日界计算
6///
7/// 所有 DateTime 均使用 UTC 时区,`Date` 为零大小结构体(无状态)。
8pub struct Date;
9
10impl Date {
11    /// 获取当前 UTC 时间
12    pub fn now() -> DateTime<Utc> { Utc::now() }
13
14    /// 获取当前本地时间
15    pub fn now_local() -> DateTime<Local> { Local::now() }
16
17    /// 日期格式化
18    pub fn fmt(dt: &DateTime<Utc>, fmt: &str) -> String {
19        dt.format(fmt).to_string()
20    }
21
22    /// 从时间戳创建 DateTime
23    pub fn from_timestamp(ts: i64) -> DateTime<Utc> {
24        DateTime::from_timestamp(ts, 0).unwrap_or_default()
25    }
26
27    /// 相对时间描述(如:3分钟前、2小时前)
28    pub fn relative(ts: i64) -> String {
29        let then = DateTime::from_timestamp(ts, 0).unwrap_or_default();
30        let diff = Utc::now() - then;
31
32        if diff.num_seconds() < 60 { format!("{}秒前", diff.num_seconds()) }
33        else if diff.num_minutes() < 60 { format!("{}分钟前", diff.num_minutes()) }
34        else if diff.num_hours() < 24 { format!("{}小时前", diff.num_hours()) }
35        else if diff.num_days() < 30 { format!("{}天前", diff.num_days()) }
36        else if diff.num_days() < 365 { format!("{}个月前", diff.num_days() / 30) }
37        else { format!("{}年前", diff.num_days() / 365) }
38    }
39
40    /// 获取当天的起始时刻(00:00:00 UTC)
41    pub fn begin_of_day(dt: &DateTime<Utc>) -> DateTime<Utc> {
42        dt.date_naive().and_hms_opt(0, 0, 0).unwrap()
43            .and_utc()
44    }
45
46    /// 获取当天的结束时刻(23:59:59 UTC)
47    pub fn end_of_day(dt: &DateTime<Utc>) -> DateTime<Utc> {
48        dt.date_naive().and_hms_opt(23, 59, 59).unwrap()
49            .and_utc()
50    }
51}