Skip to main content

Crate chrono_bounds

Crate chrono_bounds 

Source
Expand description

§chrono-bounds — period-boundary helpers for chrono

Round a chrono date or date-time down to the start of a period, or up to the end of it: day, week, month, quarter, and year. The equivalent of date-fns’ startOf/endOf, Go’s jinzhu/now, and Python pendulum’s start_of/end_of. Works on NaiveDate and NaiveDateTime, and is #![no_std] with no extra dependencies beyond chrono itself.

use chrono::{NaiveDate, Weekday};
use chrono_bounds::DateBounds;

let d = NaiveDate::from_ymd_opt(2024, 2, 10).unwrap();
assert_eq!(d.end_of_month(), NaiveDate::from_ymd_opt(2024, 2, 29).unwrap()); // leap
assert_eq!(d.start_of_quarter(), NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());
assert_eq!(d.start_of_week(Weekday::Mon), NaiveDate::from_ymd_opt(2024, 2, 5).unwrap());

For a NaiveDateTime, a start boundary sets the time to 00:00:00 and an end boundary to 23:59:59.999999999.

use chrono::NaiveDate;
use chrono_bounds::DateTimeBounds;

let t = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap().and_hms_opt(13, 45, 30).unwrap();
assert_eq!(t.start_of_day(), NaiveDate::from_ymd_opt(2024, 6, 15).unwrap().and_hms_opt(0, 0, 0).unwrap());
assert_eq!(t.start_of_hour(), NaiveDate::from_ymd_opt(2024, 6, 15).unwrap().and_hms_opt(13, 0, 0).unwrap());

Only timezone-naive types are supported in this release, so there is no DST ambiguity. Week boundaries take the day the week starts on, so any convention (Monday, Sunday, …) works.

Traits§

DateBounds
Period boundaries for a calendar date (NaiveDate).
DateTimeBounds
Period boundaries for a naive date-time (NaiveDateTime).