@@ -112,13 +112,37 @@ impl NaiveWeek {
112
112
#[ inline]
113
113
#[ must_use]
114
114
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 > {
115
139
let end = self . start . pred ( ) . num_days_from_monday ( ) as i32 ;
116
140
let ref_day = self . date . weekday ( ) . num_days_from_monday ( ) as i32 ;
117
141
// Calculate the number of days to add to `self.date`.
118
142
// Do not construct an intermediate date before `self.date` (like with `first_day()`),
119
143
// because that may be out of range if `date` is close to `NaiveDate::MIN`.
120
144
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)
122
146
}
123
147
124
148
/// Returns a [`RangeInclusive<T>`] representing the whole week bounded by
0 commit comments