1use chrono::{DateTime, Utc, Local};
4
5pub struct Date;
9
10impl Date {
11 pub fn now() -> DateTime<Utc> { Utc::now() }
13
14 pub fn now_local() -> DateTime<Local> { Local::now() }
16
17 pub fn fmt(dt: &DateTime<Utc>, fmt: &str) -> String {
19 dt.format(fmt).to_string()
20 }
21
22 pub fn from_timestamp(ts: i64) -> DateTime<Utc> {
24 DateTime::from_timestamp(ts, 0).unwrap_or_default()
25 }
26
27 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 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 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}