Adjust DateTime::now() by adding DateTimeError

This commit is contained in:
Nathan Fisher 2024-06-16 23:48:38 -04:00
parent ffea975527
commit e1c975ba74
2 changed files with 31 additions and 2 deletions

View File

@ -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<SystemTimeError> for Error {
fn from(value: SystemTimeError) -> Self {
Self::System(value)
}
}
impl From<TryFromIntError> 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<Self, SystemTimeError> {
pub fn now() -> Result<Self, Error> {
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)]

View File

@ -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;