mirror of
https://github.com/chronotope/chrono.git
synced 2025-09-28 05:21:39 +00:00
Add checked_first_day
This commit is contained in:
parent
37ec019f86
commit
68afd5b407
@ -60,13 +60,37 @@ impl NaiveWeek {
|
|||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn first_day(&self) -> NaiveDate {
|
pub const fn first_day(&self) -> NaiveDate {
|
||||||
|
expect(self.checked_first_day(), "first weekday out of range for `NaiveDate`")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a date representing the first day of the week or
|
||||||
|
/// `None` if the date is out of `NaiveDate`'s range
|
||||||
|
/// (more than ca. 262,000 years away from common era).
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use chrono::{NaiveDate, Weekday};
|
||||||
|
///
|
||||||
|
/// let date = NaiveDate::MIN;
|
||||||
|
/// let week = date.week(Weekday::Mon);
|
||||||
|
/// if let Some(first_day) = week.checked_first_day() {
|
||||||
|
/// assert!(first_day == date);
|
||||||
|
/// } else {
|
||||||
|
/// // error handling code
|
||||||
|
/// return;
|
||||||
|
/// };
|
||||||
|
/// ```
|
||||||
|
#[inline]
|
||||||
|
#[must_use]
|
||||||
|
pub const fn checked_first_day(&self) -> Option<NaiveDate> {
|
||||||
let start = self.start.num_days_from_monday() as i32;
|
let start = self.start.num_days_from_monday() as i32;
|
||||||
let ref_day = self.date.weekday().num_days_from_monday() as i32;
|
let ref_day = self.date.weekday().num_days_from_monday() as i32;
|
||||||
// Calculate the number of days to subtract from `self.date`.
|
// Calculate the number of days to subtract from `self.date`.
|
||||||
// Do not construct an intermediate date beyond `self.date`, because that may be out of
|
// Do not construct an intermediate date beyond `self.date`, because that may be out of
|
||||||
// range if `date` is close to `NaiveDate::MAX`.
|
// range if `date` is close to `NaiveDate::MAX`.
|
||||||
let days = start - ref_day - if start > ref_day { 7 } else { 0 };
|
let days = start - ref_day - if start > ref_day { 7 } else { 0 };
|
||||||
expect(self.date.add_days(days), "first weekday out of range for `NaiveDate`")
|
self.date.add_days(days)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a date representing the last day of the week.
|
/// Returns a date representing the last day of the week.
|
||||||
|
Loading…
x
Reference in New Issue
Block a user