From e1c975ba74196aec390a28bb4170cf1ebb584625 Mon Sep 17 00:00:00 2001 From: Nathan Fisher Date: Sun, 16 Jun 2024 23:48:38 -0400 Subject: [PATCH] Adjust DateTime::now() by adding DateTimeError --- src/datetime.rs | 32 ++++++++++++++++++++++++++++++-- src/lib.rs | 1 + 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/datetime.rs b/src/datetime.rs index d82df5b..04279f5 100644 --- a/src/datetime.rs +++ b/src/datetime.rs @@ -8,10 +8,38 @@ use { }, std::{ cmp, fmt, + num::TryFromIntError, time::{SystemTime, SystemTimeError, UNIX_EPOCH}, }, }; +#[derive(Debug)] +pub enum Error { + System(SystemTimeError), + RangeError, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::System(e) => write!(f, "{e}"), + Self::RangeError => write!(f, "self:?"), + } + } +} + +impl From for Error { + fn from(value: SystemTimeError) -> Self { + Self::System(value) + } +} + +impl From for Error { + fn from(_value: TryFromIntError) -> Self { + Self::RangeError + } +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub struct DateTime { @@ -154,9 +182,9 @@ impl DateTime { #[allow(clippy::missing_panics_doc)] /// Creates a `DateTime` from the system time - pub fn now() -> Result { + pub fn now() -> Result { let now = SystemTime::now().duration_since(UNIX_EPOCH)?; - Ok(Self::from_timestamp(i64::try_from(now.as_secs()).unwrap())) + Ok(Self::from_timestamp(i64::try_from(now.as_secs())?)) } #[allow(clippy::missing_panics_doc)] diff --git a/src/lib.rs b/src/lib.rs index 4fdfc4c..ee2a454 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,6 +9,7 @@ pub(crate) mod zone; pub mod prelude; pub use datetime::DateTime; +pub use datetime::Error as DateTimeError; pub static SECONDS_PER_MINUTE: i64 = 60; pub static SECONDS_PER_HOUR: i64 = 60 * 60;