Add DateTime::now method

This commit is contained in:
Nathan Fisher 2024-05-19 18:54:50 -04:00
parent 43f39fe226
commit ffea975527

View File

@ -6,7 +6,10 @@ use {
month::Month, weekday::Weekday, year::Year, zone::TimeZone, SECONDS_PER_DAY, month::Month, weekday::Weekday, year::Year, zone::TimeZone, SECONDS_PER_DAY,
SECONDS_PER_HOUR, SECONDS_PER_MINUTE, SECONDS_PER_HOUR, SECONDS_PER_MINUTE,
}, },
std::{cmp, fmt}, std::{
cmp, fmt,
time::{SystemTime, SystemTimeError, UNIX_EPOCH},
},
}; };
#[derive(Clone, Copy, Debug, Eq, PartialEq)] #[derive(Clone, Copy, Debug, Eq, PartialEq)]
@ -149,13 +152,22 @@ impl DateTime {
} }
} }
#[allow(clippy::missing_panics_doc)]
/// Creates a `DateTime` from the system time
pub fn now() -> Result<Self, SystemTimeError> {
let now = SystemTime::now().duration_since(UNIX_EPOCH)?;
Ok(Self::from_timestamp(i64::try_from(now.as_secs()).unwrap()))
}
#[allow(clippy::missing_panics_doc)] #[allow(clippy::missing_panics_doc)]
/// Gets the day of the week for this `DateTime` /// Gets the day of the week for this `DateTime`
pub fn weekday(&self) -> Weekday { pub fn weekday(&self) -> Weekday {
let ts = self.timestamp_naive(); let ts = self.timestamp_naive();
let mut days = ts / SECONDS_PER_DAY; let mut days = ts / SECONDS_PER_DAY;
// For negative timestamps this number is actually the following day // For negative timestamps this number is actually the following day
if ts < 0 { days -= 1 } if ts < 0 {
days -= 1;
}
// Rusts `%` operator is modulo, not modulus. We have to use the // Rusts `%` operator is modulo, not modulus. We have to use the
// operation which will gove the correct answer for either positive // operation which will gove the correct answer for either positive
// or negative remainders // or negative remainders