Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/datetime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1928,7 +1928,14 @@ impl From<SystemTime> for DateTime<Utc> {
if nsec == 0 { (-sec, 0) } else { (-sec - 1, 1_000_000_000 - nsec) }
}
};
Utc.timestamp_opt(sec, nsec).unwrap()
// This conversion is infallible, but the `SystemTime` may be outside the
// range of `DateTime`. Saturate to the representable bounds instead of
// panicking on `.unwrap()`.
match Utc.timestamp_opt(sec, nsec).single() {
Some(dt) => dt,
None if sec < 0 => DateTime::<Utc>::MIN_UTC,
None => DateTime::<Utc>::MAX_UTC,
}
}
}

Expand Down
6 changes: 6 additions & 0 deletions src/datetime/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1418,6 +1418,12 @@ fn test_from_system_time() {
.unwrap()
);

// A `SystemTime` outside the range of `DateTime` saturates to the bounds
// instead of panicking (see #1802).
let out_of_range = Duration::from_secs(10_000_000_000_000);
assert_eq!(DateTime::<Utc>::from(UNIX_EPOCH + out_of_range), DateTime::<Utc>::MAX_UTC);
assert_eq!(DateTime::<Utc>::from(UNIX_EPOCH - out_of_range), DateTime::<Utc>::MIN_UTC);

// DateTime<Utc> -> SystemTime
assert_eq!(SystemTime::from(epoch), UNIX_EPOCH);
assert_eq!(
Expand Down
Loading