Skip to main content

doido_core/
time_ext.rs

1//! Time/date conveniences (Rails `2.days.ago`, `beginning_of_day`, …).
2
3use chrono::{DateTime, Duration, TimeZone, Timelike, Utc};
4
5/// `n` days before now (Rails `n.days.ago`).
6pub fn days_ago(n: i64) -> DateTime<Utc> {
7    Utc::now() - Duration::days(n)
8}
9
10/// `n` days after now (Rails `n.days.from_now`).
11pub fn days_from_now(n: i64) -> DateTime<Utc> {
12    Utc::now() + Duration::days(n)
13}
14
15/// `n` hours before now.
16pub fn hours_ago(n: i64) -> DateTime<Utc> {
17    Utc::now() - Duration::hours(n)
18}
19
20/// Midnight at the start of `dt`'s day (Rails `beginning_of_day`).
21pub fn beginning_of_day<Tz: TimeZone>(dt: DateTime<Tz>) -> DateTime<Tz> {
22    dt.with_hour(0)
23        .and_then(|d| d.with_minute(0))
24        .and_then(|d| d.with_second(0))
25        .and_then(|d| d.with_nanosecond(0))
26        .unwrap_or(dt)
27}
28
29/// The last second of `dt`'s day (Rails `end_of_day`).
30pub fn end_of_day<Tz: TimeZone>(dt: DateTime<Tz>) -> DateTime<Tz> {
31    dt.with_hour(23)
32        .and_then(|d| d.with_minute(59))
33        .and_then(|d| d.with_second(59))
34        .and_then(|d| d.with_nanosecond(0))
35        .unwrap_or(dt)
36}