From 9c7f28338b1ec35f714ce5de705b7d8273105041 Mon Sep 17 00:00:00 2001 From: Nathan Fisher Date: Tue, 17 Dec 2024 00:19:19 -0500 Subject: [PATCH] Add functioons to add seconods, convert timezones and create new timespecs using a given timezone --- src/datetime.rs | 29 ++++++++++++++++++++++++++++- src/zone.rs | 2 +- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/datetime.rs b/src/datetime.rs index 04279f5..481af5a 100644 --- a/src/datetime.rs +++ b/src/datetime.rs @@ -89,7 +89,7 @@ impl DateTime { /// Gets the Unix timestamp corresponding to this `DateTime` pub fn timestamp(&self) -> i64 { let mut seconds = self.timestamp_naive(); - seconds += self.zone.as_seconds(); + seconds -= self.zone.as_seconds(); seconds } @@ -187,6 +187,27 @@ impl DateTime { Ok(Self::from_timestamp(i64::try_from(now.as_secs())?)) } + /// Converts this datetime to a different timezone + pub fn convert_timezone(&mut self, zone:TimeZone) { + let ts = self.timestamp() + zone.as_seconds(); + *self = Self::from_timestamp(ts); + self.zone = zone; + } + + /// Converts a Unix timestamp to a `DateTime` struct with the given timezone + pub fn from_timestamp_with_zone(ts: i64, zone: TimeZone) -> Self { + let mut dt = Self::from_timestamp(ts); + dt.convert_timezone(zone); + dt + } + + /// Creates a `DateTime` from the system time using the given timmezone + pub fn now_with_zone(zone: TimeZone) -> Result { + let mut dt = Self::now()?; + dt.convert_timezone(zone); + Ok(dt) + } + #[allow(clippy::missing_panics_doc)] /// Gets the day of the week for this `DateTime` pub fn weekday(&self) -> Weekday { @@ -217,6 +238,12 @@ impl DateTime { self.year(), ) } + + /// Adds the given number of seconds to this timespec + pub fn add_seconds(&mut self, seconds: i64) { + let ts = self.timestamp() + seconds; + *self = Self::from_timestamp(ts); + } } impl fmt::Display for DateTime { diff --git a/src/zone.rs b/src/zone.rs index 85ccad1..c33b062 100644 --- a/src/zone.rs +++ b/src/zone.rs @@ -91,7 +91,7 @@ impl TimeZone { } => { let base = i64::from(*hours) * SECONDS_PER_HOUR + i64::from(*minutes) * 60; if let Sign::Negative = sign { - -base + 0 - base } else { base }