From ffea97552707b6db49971d0390409eb6c11bc5d7 Mon Sep 17 00:00:00 2001 From: Nathan Fisher Date: Sun, 19 May 2024 18:54:50 -0400 Subject: [PATCH] Add `DateTime::now` method --- src/datetime.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/datetime.rs b/src/datetime.rs index 4388415..d82df5b 100644 --- a/src/datetime.rs +++ b/src/datetime.rs @@ -6,7 +6,10 @@ use { month::Month, weekday::Weekday, year::Year, zone::TimeZone, SECONDS_PER_DAY, SECONDS_PER_HOUR, SECONDS_PER_MINUTE, }, - std::{cmp, fmt}, + std::{ + cmp, fmt, + time::{SystemTime, SystemTimeError, UNIX_EPOCH}, + }, }; #[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 { + let now = SystemTime::now().duration_since(UNIX_EPOCH)?; + Ok(Self::from_timestamp(i64::try_from(now.as_secs()).unwrap())) + } + #[allow(clippy::missing_panics_doc)] /// Gets the day of the week for this `DateTime` pub fn weekday(&self) -> Weekday { let ts = self.timestamp_naive(); let mut days = ts / SECONDS_PER_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 // operation which will gove the correct answer for either positive // or negative remainders