Skip to content

Commit

Permalink
Convert TryFrom<DateTime<Tz>> for SystemTime
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed Mar 16, 2024
1 parent 64bc6a0 commit 6586aff
Showing 1 changed file with 4 additions and 5 deletions.
9 changes: 4 additions & 5 deletions src/datetime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1759,16 +1759,15 @@ impl TryFrom<SystemTime> for DateTime<Local> {

#[cfg(feature = "std")]
impl<Tz: TimeZone> TryFrom<DateTime<Tz>> for SystemTime {
type Error = OutOfRange;
type Error = Error;

fn try_from(dt: DateTime<Tz>) -> Result<SystemTime, OutOfRange> {
fn try_from(dt: DateTime<Tz>) -> Result<SystemTime, Error> {
let sec = dt.timestamp();
let sec_abs = sec.unsigned_abs();
let nsec = dt.timestamp_subsec_nanos();
if sec < 0 {
// `dt` is before the Unix epoch.
let mut t =
UNIX_EPOCH.checked_sub(Duration::new(sec_abs, 0)).ok_or_else(OutOfRange::new)?;
let mut t = UNIX_EPOCH.checked_sub(Duration::new(sec_abs, 0)).ok_or(Error::OutOfRange)?;

// Overflow safety: `t` is before the Unix epoch. Adding nanoseconds therefore cannot
// overflow.
Expand All @@ -1777,7 +1776,7 @@ impl<Tz: TimeZone> TryFrom<DateTime<Tz>> for SystemTime {
Ok(t)
} else {
// `dt` is after the Unix epoch.
UNIX_EPOCH.checked_add(Duration::new(sec_abs, nsec)).ok_or_else(OutOfRange::new)
UNIX_EPOCH.checked_add(Duration::new(sec_abs, nsec)).ok_or(Error::OutOfRange)
}
}
}
Expand Down

0 comments on commit 6586aff

Please sign in to comment.