From cf2673d4d4bc8d6b96f4488847d8c2b3c3545010 Mon Sep 17 00:00:00 2001 From: Botahamec Date: Mon, 21 Mar 2022 22:00:30 -0400 Subject: Add seconds or nanoseconds to DateTime --- src/datetime.rs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) (limited to 'src/datetime.rs') diff --git a/src/datetime.rs b/src/datetime.rs index 9332de1..49506e3 100644 --- a/src/datetime.rs +++ b/src/datetime.rs @@ -30,6 +30,16 @@ impl DateTime { } } + pub fn from_local(local_datetime: NaiveDateTime, timezone: Tz) -> Result { + let offset = timezone.offset_from_local_naive(local_datetime)?; + // TODO overflow + let utc_datetime = local_datetime + .add_seconds_overflowing(-offset.seconds_ahead() as i64) + .0; + + Ok(Self::from_utc(utc_datetime, timezone)) + } + pub fn offset(&self) -> UtcOffset { let utc = self.as_utc(); self.timezone.utc_offset(utc) @@ -69,6 +79,26 @@ impl DateTime { pub fn tai_timestamp(&self) -> UnixTimestamp { self.as_tai().to_naive_overflowing().0.timestamp() } + + #[must_use] + pub fn add_seconds_overflowing(self, seconds: i64) -> (Self, bool) { + let (tai_timestamp, overflow) = self.tai_timestamp().add_seconds_overflowing(seconds); + let tai_naive_dt = NaiveDateTime::from_timestamp(tai_timestamp); + let tai_dt = DateTime::from_local(tai_naive_dt, Tai).unwrap(); + + (tai_dt.into_timezone(self.timezone), overflow) + } + + #[must_use] + pub fn add_nanoseconds_overflowing(self, nanoseconds: i64) -> (Self, bool) { + let (tai_timestamp, overflow) = self + .tai_timestamp() + .add_nanoseconds_overflowing(nanoseconds); + let tai_naive_dt = NaiveDateTime::from_timestamp(tai_timestamp); + let tai_dt = DateTime::from_local(tai_naive_dt, Tai).unwrap(); + + (tai_dt.into_timezone(self.timezone), overflow) + } } impl NaiveDateTime { @@ -285,7 +315,7 @@ impl PartialEq> for DateTime } impl Hash for DateTime { - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.utc_datetime.hash(state); } } -- cgit v1.2.3