Add functioons to add seconods, convert timezones and create new

timespecs using a given timezone
This commit is contained in:
Nathan Fisher 2024-12-17 00:19:19 -05:00
parent e1c975ba74
commit 9c7f28338b
2 changed files with 29 additions and 2 deletions

View File

@ -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<Self, Error> {
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 {

View File

@ -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
}