Skip to content

Commit ccb04bc

Browse files
bragov4ikdjc
authored andcommitted
Add checked_last_day
1 parent 68afd5b commit ccb04bc

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

src/naive/mod.rs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,13 +112,37 @@ impl NaiveWeek {
112112
#[inline]
113113
#[must_use]
114114
pub const fn last_day(&self) -> NaiveDate {
115+
expect(self.checked_last_day(), "last weekday out of range for `NaiveDate`")
116+
}
117+
118+
/// Returns a date representing the last day of the week or
119+
/// `None` if the date is out of `NaiveDate`'s range
120+
/// (more than ca. 262,000 years away from common era).
121+
///
122+
/// # Examples
123+
///
124+
/// ```
125+
/// use chrono::{NaiveDate, Weekday};
126+
///
127+
/// let date = NaiveDate::MAX;
128+
/// let week = date.week(Weekday::Mon);
129+
/// if let Some(last_day) = week.checked_last_day() {
130+
/// assert!(last_day == date);
131+
/// } else {
132+
/// // error handling code
133+
/// return;
134+
/// };
135+
/// ```
136+
#[inline]
137+
#[must_use]
138+
pub const fn checked_last_day(&self) -> Option<NaiveDate> {
115139
let end = self.start.pred().num_days_from_monday() as i32;
116140
let ref_day = self.date.weekday().num_days_from_monday() as i32;
117141
// Calculate the number of days to add to `self.date`.
118142
// Do not construct an intermediate date before `self.date` (like with `first_day()`),
119143
// because that may be out of range if `date` is close to `NaiveDate::MIN`.
120144
let days = end - ref_day + if end < ref_day { 7 } else { 0 };
121-
expect(self.date.add_days(days), "last weekday out of range for `NaiveDate`")
145+
self.date.add_days(days)
122146
}
123147

124148
/// Returns a [`RangeInclusive<T>`] representing the whole week bounded by

0 commit comments

Comments
 (0)