Skip to content

Commit 0c97bfe

Browse files
committed
Convert NaiveDate::with_year to return Result
1 parent 6c68842 commit 0c97bfe

File tree

4 files changed

+41
-54
lines changed

4 files changed

+41
-54
lines changed

src/datetime/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -570,7 +570,7 @@ impl<Tz: TimeZone> DateTime<Tz> {
570570
pub fn with_year(&self, year: i32) -> Option<DateTime<Tz>> {
571571
map_local(self, |dt| match dt.year() == year {
572572
true => Some(dt),
573-
false => dt.with_year(year),
573+
false => dt.with_year(year).ok(),
574574
})
575575
}
576576

src/naive/date/mod.rs

Lines changed: 20 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1201,52 +1201,46 @@ impl NaiveDate {
12011201
///
12021202
/// # Errors
12031203
///
1204-
/// Returns `None` if:
1205-
/// - The resulting date does not exist (February 29 in a non-leap year).
1206-
/// - The year is out of range for a `NaiveDate`.
1204+
/// - Returns [`Error::DoesNotExist`] when the resulting date does not exist.
1205+
/// - Returns [`Error::OutOfRange`] if `year` is out of range for a `NaiveDate`.
12071206
///
12081207
/// # Examples
12091208
///
12101209
/// ```
1211-
/// use chrono::NaiveDate;
1212-
///
1213-
/// assert_eq!(
1214-
/// NaiveDate::from_ymd(2015, 9, 8).unwrap().with_year(2016),
1215-
/// Some(NaiveDate::from_ymd(2016, 9, 8).unwrap())
1216-
/// );
1217-
/// assert_eq!(
1218-
/// NaiveDate::from_ymd(2015, 9, 8).unwrap().with_year(-308),
1219-
/// Some(NaiveDate::from_ymd(-308, 9, 8).unwrap())
1220-
/// );
1210+
/// # use chrono::{NaiveDate, Error};
1211+
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8)?.with_year(2016), NaiveDate::from_ymd(2016, 9, 8));
1212+
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8)?.with_year(-308), NaiveDate::from_ymd(-308, 9, 8));
1213+
/// # Ok::<(), Error>(())
12211214
/// ```
12221215
///
1223-
/// A leap day (February 29) is a case where this method can return `None`.
1216+
/// A leap day (February 29) in a non-leap year will return [`Err(Error::DoesNotExist)`].
12241217
///
12251218
/// ```
1226-
/// # use chrono::NaiveDate;
1227-
/// assert!(NaiveDate::from_ymd(2016, 2, 29).unwrap().with_year(2015).is_none());
1228-
/// assert!(NaiveDate::from_ymd(2016, 2, 29).unwrap().with_year(2020).is_some());
1219+
/// # use chrono::{NaiveDate, Error};
1220+
/// assert_eq!(NaiveDate::from_ymd(2016, 2, 29)?.with_year(2015), Err(Error::DoesNotExist));
1221+
/// assert!(NaiveDate::from_ymd(2016, 2, 29)?.with_year(2020).is_ok());
1222+
/// # Ok::<(), Error>(())
12291223
/// ```
12301224
///
1231-
/// Don't use `with_year` if you want the ordinal date to stay the same:
1225+
/// Don't use `with_year` if you want the ordinal date to stay the same.
12321226
///
12331227
/// ```
1234-
/// # use chrono::NaiveDate;
1235-
/// assert_ne!(
1236-
/// NaiveDate::from_yo(2020, 100).unwrap().with_year(2023).unwrap(),
1237-
/// NaiveDate::from_yo(2023, 100).unwrap() // result is 2023-101
1238-
/// );
1228+
/// # use chrono::{NaiveDate, Error};
1229+
/// let date = NaiveDate::from_yo(2020, 100)?.with_year(2023);
1230+
/// assert_ne!(date, NaiveDate::from_yo(2023, 100));
1231+
/// assert_eq!(date, NaiveDate::from_yo(2023, 99));
1232+
/// # Ok::<(), Error>(())
12391233
/// ```
12401234
#[inline]
1241-
pub const fn with_year(&self, year: i32) -> Option<NaiveDate> {
1235+
pub const fn with_year(&self, year: i32) -> Result<NaiveDate, Error> {
12421236
// we need to operate with `mdf` since we should keep the month and day number as is
12431237
let mdf = self.mdf();
12441238

12451239
// adjust the flags as needed
12461240
let flags = YearFlags::from_year(year);
12471241
let mdf = mdf.with_flags(flags);
12481242

1249-
ok!(NaiveDate::from_mdf(year, mdf))
1243+
NaiveDate::from_mdf(year, mdf)
12501244
}
12511245

12521246
/// Makes a new `NaiveDate` with the month number (starting from 1) changed.
@@ -1276,7 +1270,7 @@ impl NaiveDate {
12761270
/// use chrono::{Datelike, Error, NaiveDate};
12771271
///
12781272
/// fn with_year_month(date: NaiveDate, year: i32, month: u32) -> Option<NaiveDate> {
1279-
/// date.with_year(year)?.with_month(month)
1273+
/// date.with_year(year).ok()?.with_month(month)
12801274
/// }
12811275
/// let d = NaiveDate::from_ymd(2020, 2, 29).unwrap();
12821276
/// assert!(with_year_month(d, 2019, 1).is_none()); // fails because of invalid intermediate value

src/naive/date/tests.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -367,14 +367,14 @@ fn test_date_weekday() {
367367
#[test]
368368
fn test_date_with_fields() {
369369
let d = NaiveDate::from_ymd(2000, 2, 29).unwrap();
370-
assert_eq!(d.with_year(-400), Some(NaiveDate::from_ymd(-400, 2, 29).unwrap()));
371-
assert_eq!(d.with_year(-100), None);
372-
assert_eq!(d.with_year(1600), Some(NaiveDate::from_ymd(1600, 2, 29).unwrap()));
373-
assert_eq!(d.with_year(1900), None);
374-
assert_eq!(d.with_year(2000), Some(NaiveDate::from_ymd(2000, 2, 29).unwrap()));
375-
assert_eq!(d.with_year(2001), None);
376-
assert_eq!(d.with_year(2004), Some(NaiveDate::from_ymd(2004, 2, 29).unwrap()));
377-
assert_eq!(d.with_year(i32::MAX), None);
370+
assert_eq!(d.with_year(-400), NaiveDate::from_ymd(-400, 2, 29));
371+
assert_eq!(d.with_year(-100), Err(Error::DoesNotExist));
372+
assert_eq!(d.with_year(1600), NaiveDate::from_ymd(1600, 2, 29));
373+
assert_eq!(d.with_year(1900), Err(Error::DoesNotExist));
374+
assert_eq!(d.with_year(2000), NaiveDate::from_ymd(2000, 2, 29));
375+
assert_eq!(d.with_year(2001), Err(Error::DoesNotExist));
376+
assert_eq!(d.with_year(2004), NaiveDate::from_ymd(2004, 2, 29));
377+
assert_eq!(d.with_year(i32::MAX), Err(Error::OutOfRange));
378378

379379
let d = NaiveDate::from_ymd(2000, 4, 30).unwrap();
380380
assert_eq!(d.with_month(0), None);

src/naive/datetime/mod.rs

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ use crate::format::{Fixed, Item, Numeric, Pad};
2020
use crate::naive::{Days, IsoWeek, NaiveDate, NaiveTime};
2121
use crate::offset::Utc;
2222
use crate::{
23-
expect, ok, try_opt, DateTime, Datelike, FixedOffset, LocalResult, Months, TimeDelta, TimeZone,
24-
Timelike, Weekday,
23+
expect, ok, try_err, try_opt, DateTime, Datelike, Error, FixedOffset, LocalResult, Months,
24+
TimeDelta, TimeZone, Timelike, Weekday,
2525
};
2626

2727
/// Tools to help serializing/deserializing `NaiveDateTime`s
@@ -728,28 +728,21 @@ impl NaiveDateTime {
728728
///
729729
/// # Errors
730730
///
731-
/// Returns `None` if:
732-
/// - The resulting date does not exist (February 29 in a non-leap year).
733-
/// - The year is out of range for a `NaiveDate`.
731+
/// - Returns [`Error::DoesNotExist`] when the resulting date does not exist.
732+
/// - Returns [`Error::OutOfRange`] if `year` is out of range for a `NaiveDate`.
734733
///
735-
/// # Example
734+
/// # Examples
736735
///
737736
/// ```
738-
/// use chrono::{NaiveDate, NaiveDateTime};
739-
///
740-
/// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 25).unwrap().and_hms(12, 34, 56).unwrap();
741-
/// assert_eq!(
742-
/// dt.with_year(2016),
743-
/// Some(NaiveDate::from_ymd(2016, 9, 25).unwrap().and_hms(12, 34, 56).unwrap())
744-
/// );
745-
/// assert_eq!(
746-
/// dt.with_year(-308),
747-
/// Some(NaiveDate::from_ymd(-308, 9, 25).unwrap().and_hms(12, 34, 56).unwrap())
748-
/// );
737+
/// # use chrono::{NaiveDate, NaiveDateTime, Error};
738+
/// let dt: NaiveDateTime = NaiveDate::from_ymd(2015, 9, 25)?.and_hms(12, 34, 56)?;
739+
/// assert_eq!(dt.with_year(2016), NaiveDate::from_ymd(2016, 9, 25)?.and_hms(12, 34, 56));
740+
/// assert_eq!(dt.with_year(-308), NaiveDate::from_ymd(-308, 9, 25)?.and_hms(12, 34, 56));
741+
/// # Ok::<(), Error>(())
749742
/// ```
750743
#[inline]
751-
pub const fn with_year(&self, year: i32) -> Option<NaiveDateTime> {
752-
Some(NaiveDateTime { date: try_opt!(self.date.with_year(year)), ..*self })
744+
pub const fn with_year(&self, year: i32) -> Result<NaiveDateTime, Error> {
745+
Ok(NaiveDateTime { date: try_err!(self.date.with_year(year)), ..*self })
753746
}
754747

755748
/// Makes a new `NaiveDateTime` with the month number (starting from 1) changed.

0 commit comments

Comments
 (0)