Skip to main content

chrono_bounds/
lib.rs

1//! # chrono-bounds — period-boundary helpers for chrono
2//!
3//! Round a [`chrono`] date or date-time down to the **start** of a period, or up to
4//! the **end** of it: day, week, month, quarter, and year. The equivalent of
5//! `date-fns`' `startOf`/`endOf`, Go's `jinzhu/now`, and Python `pendulum`'s
6//! `start_of`/`end_of`. Works on [`NaiveDate`] and [`NaiveDateTime`], and is
7//! `#![no_std]` with no extra dependencies beyond `chrono` itself.
8//!
9//! ```
10//! use chrono::{NaiveDate, Weekday};
11//! use chrono_bounds::DateBounds;
12//!
13//! let d = NaiveDate::from_ymd_opt(2024, 2, 10).unwrap();
14//! assert_eq!(d.end_of_month(), NaiveDate::from_ymd_opt(2024, 2, 29).unwrap()); // leap
15//! assert_eq!(d.start_of_quarter(), NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());
16//! assert_eq!(d.start_of_week(Weekday::Mon), NaiveDate::from_ymd_opt(2024, 2, 5).unwrap());
17//! ```
18//!
19//! For a [`NaiveDateTime`], a *start* boundary sets the time to `00:00:00` and an
20//! *end* boundary to `23:59:59.999999999`.
21//!
22//! ```
23//! use chrono::NaiveDate;
24//! use chrono_bounds::DateTimeBounds;
25//!
26//! let t = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap().and_hms_opt(13, 45, 30).unwrap();
27//! assert_eq!(t.start_of_day(), NaiveDate::from_ymd_opt(2024, 6, 15).unwrap().and_hms_opt(0, 0, 0).unwrap());
28//! assert_eq!(t.start_of_hour(), NaiveDate::from_ymd_opt(2024, 6, 15).unwrap().and_hms_opt(13, 0, 0).unwrap());
29//! ```
30//!
31//! Only timezone-naive types are supported in this release, so there is no DST
32//! ambiguity. Week boundaries take the day the week starts on, so any convention
33//! (Monday, Sunday, …) works.
34
35#![no_std]
36#![doc(html_root_url = "https://docs.rs/chrono-bounds/0.1.0")]
37
38use chrono::{Datelike, Days, NaiveDate, NaiveDateTime, Timelike, Weekday};
39
40// Compile-test the README's examples as part of `cargo test`.
41#[cfg(doctest)]
42#[doc = include_str!("../README.md")]
43struct ReadmeDoctests;
44
45/// The last nanosecond of a second, used for *end* boundaries.
46const END_NANO: u32 = 999_999_999;
47
48/// Whether `year` is a leap year in the proleptic Gregorian calendar.
49const fn is_leap_year(year: i32) -> bool {
50    year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
51}
52
53/// The number of days in `month` (1–12) of `year`.
54const fn days_in_month(year: i32, month: u32) -> u32 {
55    match month {
56        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
57        2 if is_leap_year(year) => 29,
58        2 => 28,
59        // 4, 6, 9, 11 — and, harmlessly, any out-of-range month.
60        _ => 30,
61    }
62}
63
64/// The first month (1, 4, 7, or 10) of the quarter containing `month`.
65const fn quarter_start_month(month: u32) -> u32 {
66    (month - 1) / 3 * 3 + 1
67}
68
69/// Period boundaries for a calendar date ([`NaiveDate`]).
70pub trait DateBounds: Sized {
71    /// The first day of the week containing `self`, given the day the week starts on.
72    #[must_use]
73    fn start_of_week(self, week_start: Weekday) -> Self;
74    /// The last day of the week containing `self`, given the day the week starts on.
75    #[must_use]
76    fn end_of_week(self, week_start: Weekday) -> Self;
77    /// The first day of the month containing `self`.
78    #[must_use]
79    fn start_of_month(self) -> Self;
80    /// The last day of the month containing `self`.
81    #[must_use]
82    fn end_of_month(self) -> Self;
83    /// The first day of the quarter containing `self`.
84    #[must_use]
85    fn start_of_quarter(self) -> Self;
86    /// The last day of the quarter containing `self`.
87    #[must_use]
88    fn end_of_quarter(self) -> Self;
89    /// The first day of the year containing `self`.
90    #[must_use]
91    fn start_of_year(self) -> Self;
92    /// The last day of the year containing `self`.
93    #[must_use]
94    fn end_of_year(self) -> Self;
95}
96
97impl DateBounds for NaiveDate {
98    fn start_of_week(self, week_start: Weekday) -> Self {
99        let offset =
100            (self.weekday().num_days_from_monday() + 7 - week_start.num_days_from_monday()) % 7;
101        self.checked_sub_days(Days::new(u64::from(offset)))
102            .unwrap_or(NaiveDate::MIN)
103    }
104
105    fn end_of_week(self, week_start: Weekday) -> Self {
106        // Compute the forward offset to the week's last day directly from `self`
107        // (the day before the next `week_start`), so the result stays correct even
108        // when the week's *start* would underflow `NaiveDate::MIN`.
109        let week_end = week_start.pred();
110        let offset =
111            (week_end.num_days_from_monday() + 7 - self.weekday().num_days_from_monday()) % 7;
112        self.checked_add_days(Days::new(u64::from(offset)))
113            .unwrap_or(NaiveDate::MAX)
114    }
115
116    fn start_of_month(self) -> Self {
117        NaiveDate::from_ymd_opt(self.year(), self.month(), 1).unwrap_or(self)
118    }
119
120    fn end_of_month(self) -> Self {
121        let last = days_in_month(self.year(), self.month());
122        NaiveDate::from_ymd_opt(self.year(), self.month(), last).unwrap_or(self)
123    }
124
125    fn start_of_quarter(self) -> Self {
126        let month = quarter_start_month(self.month());
127        NaiveDate::from_ymd_opt(self.year(), month, 1).unwrap_or(self)
128    }
129
130    fn end_of_quarter(self) -> Self {
131        let month = quarter_start_month(self.month()) + 2;
132        let last = days_in_month(self.year(), month);
133        NaiveDate::from_ymd_opt(self.year(), month, last).unwrap_or(self)
134    }
135
136    fn start_of_year(self) -> Self {
137        NaiveDate::from_ymd_opt(self.year(), 1, 1).unwrap_or(self)
138    }
139
140    fn end_of_year(self) -> Self {
141        NaiveDate::from_ymd_opt(self.year(), 12, 31).unwrap_or(self)
142    }
143}
144
145/// Period boundaries for a naive date-time ([`NaiveDateTime`]).
146///
147/// A *start* boundary sets the time to `00:00:00`; an *end* boundary sets it to
148/// `23:59:59.999999999` (or the analogous last instant of an hour, minute, or
149/// second).
150pub trait DateTimeBounds: Sized {
151    /// The start of the second containing `self` (nanoseconds zeroed).
152    #[must_use]
153    fn start_of_second(self) -> Self;
154    /// The end of the second containing `self`.
155    #[must_use]
156    fn end_of_second(self) -> Self;
157    /// The start of the minute containing `self`.
158    #[must_use]
159    fn start_of_minute(self) -> Self;
160    /// The end of the minute containing `self`.
161    #[must_use]
162    fn end_of_minute(self) -> Self;
163    /// The start of the hour containing `self`.
164    #[must_use]
165    fn start_of_hour(self) -> Self;
166    /// The end of the hour containing `self`.
167    #[must_use]
168    fn end_of_hour(self) -> Self;
169    /// The start of the day containing `self` (`00:00:00`).
170    #[must_use]
171    fn start_of_day(self) -> Self;
172    /// The end of the day containing `self` (`23:59:59.999999999`).
173    #[must_use]
174    fn end_of_day(self) -> Self;
175    /// The start of the week containing `self`, at `00:00:00`.
176    #[must_use]
177    fn start_of_week(self, week_start: Weekday) -> Self;
178    /// The end of the week containing `self`, at `23:59:59.999999999`.
179    #[must_use]
180    fn end_of_week(self, week_start: Weekday) -> Self;
181    /// The start of the month containing `self`, at `00:00:00`.
182    #[must_use]
183    fn start_of_month(self) -> Self;
184    /// The end of the month containing `self`, at `23:59:59.999999999`.
185    #[must_use]
186    fn end_of_month(self) -> Self;
187    /// The start of the quarter containing `self`, at `00:00:00`.
188    #[must_use]
189    fn start_of_quarter(self) -> Self;
190    /// The end of the quarter containing `self`, at `23:59:59.999999999`.
191    #[must_use]
192    fn end_of_quarter(self) -> Self;
193    /// The start of the year containing `self`, at `00:00:00`.
194    #[must_use]
195    fn start_of_year(self) -> Self;
196    /// The end of the year containing `self`, at `23:59:59.999999999`.
197    #[must_use]
198    fn end_of_year(self) -> Self;
199}
200
201/// Attach `00:00:00` to a date, falling back to `original` on the impossible
202/// out-of-range case (keeps the API panic-free).
203fn at_start(date: NaiveDate, original: NaiveDateTime) -> NaiveDateTime {
204    date.and_hms_opt(0, 0, 0).unwrap_or(original)
205}
206
207/// Attach `23:59:59.999999999` to a date, with the same panic-free fallback.
208fn at_end(date: NaiveDate, original: NaiveDateTime) -> NaiveDateTime {
209    ensure_after(
210        date.and_hms_nano_opt(23, 59, 59, END_NANO)
211            .unwrap_or(original),
212        original,
213    )
214}
215
216/// An end-of-period instant must never precede its input. The only input for which a
217/// naive `23:59:59.999999999` end could fall *before* it is a leap-second instant
218/// (chrono encodes `23:59:60.x` with nanosecond ≥ 1e9): extend the candidate into the
219/// leap slot so the boundary still lands on or after `original`.
220fn ensure_after(candidate: NaiveDateTime, original: NaiveDateTime) -> NaiveDateTime {
221    if candidate < original {
222        candidate
223            .with_nanosecond(1_999_999_999)
224            .unwrap_or(original)
225            .max(original)
226    } else {
227        candidate
228    }
229}
230
231impl DateTimeBounds for NaiveDateTime {
232    fn start_of_second(self) -> Self {
233        self.with_nanosecond(0).unwrap_or(self)
234    }
235
236    fn end_of_second(self) -> Self {
237        ensure_after(self.with_nanosecond(END_NANO).unwrap_or(self), self)
238    }
239
240    fn start_of_minute(self) -> Self {
241        self.date()
242            .and_hms_opt(self.hour(), self.minute(), 0)
243            .unwrap_or(self)
244    }
245
246    fn end_of_minute(self) -> Self {
247        ensure_after(
248            self.date()
249                .and_hms_nano_opt(self.hour(), self.minute(), 59, END_NANO)
250                .unwrap_or(self),
251            self,
252        )
253    }
254
255    fn start_of_hour(self) -> Self {
256        self.date().and_hms_opt(self.hour(), 0, 0).unwrap_or(self)
257    }
258
259    fn end_of_hour(self) -> Self {
260        ensure_after(
261            self.date()
262                .and_hms_nano_opt(self.hour(), 59, 59, END_NANO)
263                .unwrap_or(self),
264            self,
265        )
266    }
267
268    fn start_of_day(self) -> Self {
269        at_start(self.date(), self)
270    }
271
272    fn end_of_day(self) -> Self {
273        at_end(self.date(), self)
274    }
275
276    fn start_of_week(self, week_start: Weekday) -> Self {
277        at_start(self.date().start_of_week(week_start), self)
278    }
279
280    fn end_of_week(self, week_start: Weekday) -> Self {
281        at_end(self.date().end_of_week(week_start), self)
282    }
283
284    fn start_of_month(self) -> Self {
285        at_start(self.date().start_of_month(), self)
286    }
287
288    fn end_of_month(self) -> Self {
289        at_end(self.date().end_of_month(), self)
290    }
291
292    fn start_of_quarter(self) -> Self {
293        at_start(self.date().start_of_quarter(), self)
294    }
295
296    fn end_of_quarter(self) -> Self {
297        at_end(self.date().end_of_quarter(), self)
298    }
299
300    fn start_of_year(self) -> Self {
301        at_start(self.date().start_of_year(), self)
302    }
303
304    fn end_of_year(self) -> Self {
305        at_end(self.date().end_of_year(), self)
306    }
307}