wordval-utils 1.0.8

Wordval utilities: string manipulation, date handling, masking, ID generation, validation, crypto, web helpers, collection tools, retry utilities
Documentation
//! 日期工具:格式化、相对时间、时间戳互转

use chrono::{DateTime, Datelike, Local, NaiveDate, TimeZone, Timelike, Utc, Weekday};

/// 日期工具 —— 格式化、相对时间描述、时间戳互转、日界计算
///
/// `now()` 返回 UTC,`now_local()` 返回本地时区,`Date` 为零大小结构体(无状态)。
pub struct Date;

impl Date {
    /// 获取当前 UTC 时间
    pub fn now() -> DateTime<Utc> {
        Utc::now()
    }

    /// 获取当前本地时间
    pub fn now_local() -> DateTime<Local> {
        Local::now()
    }

    /// 当前秒级时间戳(UTC)
    pub fn now_timestamp() -> i64 {
        Utc::now().timestamp()
    }

    /// 当前毫秒时间戳(UTC)
    pub fn now_timestamp_millis() -> i64 {
        Utc::now().timestamp_millis()
    }

    /// 日期格式化(支持任意时区:UTC / Local / 固定偏移)
    pub fn fmt<Tz: TimeZone>(dt: &DateTime<Tz>, fmt: &str) -> String
    where
        Tz::Offset: std::fmt::Display,
    {
        dt.format(fmt).to_string()
    }

    /// 快捷格式化:`"2026-08-22"`
    pub fn fmt_ymd<Tz: TimeZone>(dt: &DateTime<Tz>) -> String
    where
        Tz::Offset: std::fmt::Display,
    {
        dt.format("%Y-%m-%d").to_string()
    }

    /// 快捷格式化:`"2026-08-22 15:30:00"`
    pub fn fmt_ymd_hms<Tz: TimeZone>(dt: &DateTime<Tz>) -> String
    where
        Tz::Offset: std::fmt::Display,
    {
        dt.format("%Y-%m-%d %H:%M:%S").to_string()
    }

    /// 从时间戳创建 DateTime
    pub fn from_timestamp(ts: i64) -> DateTime<Utc> {
        DateTime::from_timestamp(ts, 0).unwrap_or_default()
    }

    /// 从时间戳(毫秒)创建 DateTime
    pub fn from_timestamp_millis(ts: i64) -> DateTime<Utc> {
        let secs = ts.div_euclid(1000);
        let nsecs = ts.rem_euclid(1000) as u32 * 1_000_000;
        DateTime::from_timestamp(secs, nsecs).unwrap_or_default()
    }

    /// 相对时间描述(如:3分钟前、2小时前;未来时间显示"刚刚")
    pub fn relative(ts: i64) -> String {
        let then = DateTime::from_timestamp(ts, 0).unwrap_or_default();
        let diff = Utc::now() - then;
        let secs = diff.num_seconds();
        if secs < 0 {
            // 未来时间戳,避免出现 "-3秒前"
            return "刚刚".to_string();
        }

        if secs < 60 {
            format!("{}秒前", secs)
        } else if diff.num_minutes() < 60 {
            format!("{}分钟前", diff.num_minutes())
        } else if diff.num_hours() < 24 {
            format!("{}小时前", diff.num_hours())
        } else if diff.num_days() < 30 {
            format!("{}天前", diff.num_days())
        } else if diff.num_days() < 365 {
            format!("{}个月前", diff.num_days() / 30)
        } else {
            format!("{}年前", diff.num_days() / 365)
        }
    }

    /// 获取当天的起始时刻(00:00:00 UTC)
    pub fn begin_of_day(dt: &DateTime<Utc>) -> DateTime<Utc> {
        dt.date_naive().and_hms_opt(0, 0, 0).unwrap().and_utc()
    }

    /// 获取当天的结束时刻(23:59:59 UTC)
    pub fn end_of_day(dt: &DateTime<Utc>) -> DateTime<Utc> {
        dt.date_naive().and_hms_opt(23, 59, 59).unwrap().and_utc()
    }

    /// 获取本周一的起始时刻(00:00:00 UTC)
    pub fn begin_of_week(dt: &DateTime<Utc>) -> DateTime<Utc> {
        let weekday = dt.weekday();
        let days_since_monday = weekday.num_days_from_monday();
        let monday = dt.date_naive() - chrono::Duration::days(days_since_monday as i64);
        monday.and_hms_opt(0, 0, 0).unwrap().and_utc()
    }

    /// 获取本周日的结束时刻(23:59:59 UTC)
    pub fn end_of_week(dt: &DateTime<Utc>) -> DateTime<Utc> {
        let weekday = dt.weekday();
        let days_until_sunday = 6 - weekday.num_days_from_monday();
        let sunday = dt.date_naive() + chrono::Duration::days(days_until_sunday as i64);
        sunday.and_hms_opt(23, 59, 59).unwrap().and_utc()
    }

    /// 获取月初的起始时刻(00:00:00 UTC)
    pub fn begin_of_month(dt: &DateTime<Utc>) -> DateTime<Utc> {
        let naive = dt.date_naive();
        let first = NaiveDate::from_ymd_opt(naive.year(), naive.month(), 1).unwrap();
        first.and_hms_opt(0, 0, 0).unwrap().and_utc()
    }

    /// 获取月末的结束时刻(23:59:59 UTC)
    pub fn end_of_month(dt: &DateTime<Utc>) -> DateTime<Utc> {
        let naive = dt.date_naive();
        let (year, month) = if naive.month() == 12 {
            (naive.year() + 1, 1)
        } else {
            (naive.year(), naive.month() + 1)
        };
        let first_next = NaiveDate::from_ymd_opt(year, month, 1).unwrap();
        let last = first_next - chrono::Duration::days(1);
        last.and_hms_opt(23, 59, 59).unwrap().and_utc()
    }

    /// 获取年初的起始时刻(1月1日 00:00:00 UTC)
    pub fn begin_of_year(dt: &DateTime<Utc>) -> DateTime<Utc> {
        let first = NaiveDate::from_ymd_opt(dt.year(), 1, 1).unwrap();
        first.and_hms_opt(0, 0, 0).unwrap().and_utc()
    }

    /// 获取年末的结束时刻(12月31日 23:59:59 UTC)
    pub fn end_of_year(dt: &DateTime<Utc>) -> DateTime<Utc> {
        let last = NaiveDate::from_ymd_opt(dt.year(), 12, 31).unwrap();
        last.and_hms_opt(23, 59, 59).unwrap().and_utc()
    }

    /// 两日期之间相差的天数(a - b,可正可负)
    pub fn days_between(a: &DateTime<Utc>, b: &DateTime<Utc>) -> i64 {
        (a.date_naive() - b.date_naive()).num_days()
    }

    /// 加 N 天
    pub fn add_days(dt: &DateTime<Utc>, days: i64) -> DateTime<Utc> {
        let naive = dt.date_naive() + chrono::Duration::days(days);
        naive
            .and_hms_opt(dt.hour(), dt.minute(), dt.second())
            .unwrap()
            .and_utc()
    }

    /// 是否为周末(周六或周日)
    pub fn is_weekend(dt: &DateTime<Utc>) -> bool {
        matches!(dt.weekday(), Weekday::Sat | Weekday::Sun)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_dt(year: i32, month: u32, day: u32, h: u32, m: u32, s: u32) -> DateTime<Utc> {
        NaiveDate::from_ymd_opt(year, month, day)
            .unwrap()
            .and_hms_opt(h, m, s)
            .unwrap()
            .and_utc()
    }

    #[test]
    fn test_now_timestamp() {
        let ts = Date::now_timestamp();
        assert!(ts > 1_700_000_000);
    }

    #[test]
    fn test_now_timestamp_millis() {
        let ts = Date::now_timestamp_millis();
        assert!(ts > 1_700_000_000_000);
    }

    #[test]
    fn test_fmt_ymd() {
        let dt = make_dt(2026, 8, 22, 15, 30, 0);
        assert_eq!(Date::fmt_ymd(&dt), "2026-08-22");
    }

    #[test]
    fn test_fmt_ymd_hms() {
        let dt = make_dt(2026, 8, 22, 15, 30, 45);
        assert_eq!(Date::fmt_ymd_hms(&dt), "2026-08-22 15:30:45");
    }

    #[test]
    fn test_from_timestamp_millis() {
        let dt = Date::from_timestamp_millis(1_700_000_000_123);
        assert_eq!(dt.timestamp(), 1_700_000_000);
        assert_eq!(dt.timestamp_subsec_millis(), 123);
    }

    #[test]
    fn test_begin_of_day() {
        let dt = make_dt(2026, 8, 22, 15, 30, 45);
        let begin = Date::begin_of_day(&dt);
        assert_eq!(Date::fmt_ymd_hms(&begin), "2026-08-22 00:00:00");
    }

    #[test]
    fn test_end_of_day() {
        let dt = make_dt(2026, 8, 22, 15, 30, 45);
        let end = Date::end_of_day(&dt);
        assert_eq!(Date::fmt_ymd_hms(&end), "2026-08-22 23:59:59");
    }

    #[test]
    fn test_begin_of_week_monday() {
        // 2026-08-22 is Saturday
        let dt = make_dt(2026, 8, 22, 12, 0, 0);
        let begin = Date::begin_of_week(&dt);
        // Monday is 2026-08-17
        assert_eq!(Date::fmt_ymd(&begin), "2026-08-17");
    }

    #[test]
    fn test_end_of_week_sunday() {
        // 2026-08-22 is Saturday
        let dt = make_dt(2026, 8, 22, 12, 0, 0);
        let end = Date::end_of_week(&dt);
        // Sunday is 2026-08-23
        assert_eq!(Date::fmt_ymd(&end), "2026-08-23");
    }

    #[test]
    fn test_begin_of_month() {
        let dt = make_dt(2026, 8, 22, 15, 30, 0);
        let begin = Date::begin_of_month(&dt);
        assert_eq!(Date::fmt_ymd_hms(&begin), "2026-08-01 00:00:00");
    }

    #[test]
    fn test_end_of_month() {
        let dt = make_dt(2026, 8, 22, 15, 30, 0);
        let end = Date::end_of_month(&dt);
        assert_eq!(Date::fmt_ymd_hms(&end), "2026-08-31 23:59:59");
    }

    #[test]
    fn test_end_of_month_feb_leap() {
        let dt = make_dt(2024, 2, 10, 0, 0, 0);
        let end = Date::end_of_month(&dt);
        assert_eq!(Date::fmt_ymd(&end), "2024-02-29");
    }

    #[test]
    fn test_end_of_month_dec() {
        let dt = make_dt(2026, 12, 15, 0, 0, 0);
        let end = Date::end_of_month(&dt);
        assert_eq!(Date::fmt_ymd(&end), "2026-12-31");
    }

    #[test]
    fn test_begin_of_year() {
        let dt = make_dt(2026, 8, 22, 15, 30, 0);
        let begin = Date::begin_of_year(&dt);
        assert_eq!(Date::fmt_ymd_hms(&begin), "2026-01-01 00:00:00");
    }

    #[test]
    fn test_end_of_year() {
        let dt = make_dt(2026, 8, 22, 15, 30, 0);
        let end = Date::end_of_year(&dt);
        assert_eq!(Date::fmt_ymd_hms(&end), "2026-12-31 23:59:59");
    }

    #[test]
    fn test_days_between() {
        let a = make_dt(2026, 8, 22, 0, 0, 0);
        let b = make_dt(2026, 8, 15, 0, 0, 0);
        assert_eq!(Date::days_between(&a, &b), 7);
        assert_eq!(Date::days_between(&b, &a), -7);
    }

    #[test]
    fn test_add_days() {
        let dt = make_dt(2026, 8, 22, 15, 30, 0);
        let result = Date::add_days(&dt, 10);
        assert_eq!(Date::fmt_ymd(&result), "2026-09-01");
        assert_eq!(result.hour(), 15);
        assert_eq!(result.minute(), 30);
    }

    #[test]
    fn test_add_days_negative() {
        let dt = make_dt(2026, 8, 5, 10, 0, 0);
        let result = Date::add_days(&dt, -10);
        assert_eq!(Date::fmt_ymd(&result), "2026-07-26");
    }

    #[test]
    fn test_is_weekend() {
        // 2026-08-22 is Saturday
        let sat = make_dt(2026, 8, 22, 0, 0, 0);
        assert!(Date::is_weekend(&sat));
        // 2026-08-23 is Sunday
        let sun = make_dt(2026, 8, 23, 0, 0, 0);
        assert!(Date::is_weekend(&sun));
        // 2026-08-24 is Monday
        let mon = make_dt(2026, 8, 24, 0, 0, 0);
        assert!(!Date::is_weekend(&mon));
    }
}