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 }