Skip to content

Commit e479cb8

Browse files
committed
Make with_year return Some if it is a no-op
1 parent 549c35f commit e479cb8

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

src/datetime/mod.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1026,12 +1026,15 @@ impl<Tz: TimeZone> Datelike for DateTime<Tz> {
10261026
/// # Errors
10271027
///
10281028
/// Returns `None` if:
1029-
/// - The resulting date does not exist.
1030-
/// - When the `NaiveDateTime` would be out of range.
10311029
/// - The local time at the resulting date does not exist or is ambiguous, for example during a
10321030
/// daylight saving time transition.
1031+
/// - The resulting UTC datetime would be out of range.
1032+
/// - The resulting local datetime would be out of range (unless the year remains the same).
10331033
fn with_year(&self, year: i32) -> Option<DateTime<Tz>> {
1034-
map_local(self, |datetime| datetime.with_year(year))
1034+
map_local(self, |dt| match dt.year() == year {
1035+
true => Some(dt),
1036+
false => dt.with_year(year),
1037+
})
10351038
}
10361039

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

src/datetime/tests.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1410,6 +1410,7 @@ fn test_min_max_setters() {
14101410
let beyond_max = offset_max.from_utc_datetime(&NaiveDateTime::MAX);
14111411

14121412
assert_eq!(beyond_min.with_year(2020).unwrap().year(), 2020);
1413+
assert_eq!(beyond_min.with_year(beyond_min.year()), Some(beyond_min));
14131414
assert_eq!(beyond_min.with_month(beyond_min.month()), Some(beyond_min));
14141415
assert_eq!(beyond_min.with_month(3), None);
14151416
assert_eq!(beyond_min.with_month0(beyond_min.month0()), Some(beyond_min));
@@ -1430,6 +1431,7 @@ fn test_min_max_setters() {
14301431
assert_eq!(beyond_min.with_nanosecond(0), Some(beyond_min));
14311432

14321433
assert_eq!(beyond_max.with_year(2020).unwrap().year(), 2020);
1434+
assert_eq!(beyond_max.with_year(beyond_max.year()), Some(beyond_max));
14331435
assert_eq!(beyond_max.with_month(beyond_max.month()), Some(beyond_max));
14341436
assert_eq!(beyond_max.with_month(3), None);
14351437
assert_eq!(beyond_max.with_month0(beyond_max.month0()), Some(beyond_max));

0 commit comments

Comments
 (0)