Add functioons to add seconods, convert timezones and create new
timespecs using a given timezone
This commit is contained in:
parent
e1c975ba74
commit
9c7f28338b
@ -89,7 +89,7 @@ impl DateTime {
|
|||||||
/// Gets the Unix timestamp corresponding to this `DateTime`
|
/// Gets the Unix timestamp corresponding to this `DateTime`
|
||||||
pub fn timestamp(&self) -> i64 {
|
pub fn timestamp(&self) -> i64 {
|
||||||
let mut seconds = self.timestamp_naive();
|
let mut seconds = self.timestamp_naive();
|
||||||
seconds += self.zone.as_seconds();
|
seconds -= self.zone.as_seconds();
|
||||||
seconds
|
seconds
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -187,6 +187,27 @@ impl DateTime {
|
|||||||
Ok(Self::from_timestamp(i64::try_from(now.as_secs())?))
|
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)]
|
#[allow(clippy::missing_panics_doc)]
|
||||||
/// Gets the day of the week for this `DateTime`
|
/// Gets the day of the week for this `DateTime`
|
||||||
pub fn weekday(&self) -> Weekday {
|
pub fn weekday(&self) -> Weekday {
|
||||||
@ -217,6 +238,12 @@ impl DateTime {
|
|||||||
self.year(),
|
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 {
|
impl fmt::Display for DateTime {
|
||||||
|
@ -91,7 +91,7 @@ impl TimeZone {
|
|||||||
} => {
|
} => {
|
||||||
let base = i64::from(*hours) * SECONDS_PER_HOUR + i64::from(*minutes) * 60;
|
let base = i64::from(*hours) * SECONDS_PER_HOUR + i64::from(*minutes) * 60;
|
||||||
if let Sign::Negative = sign {
|
if let Sign::Negative = sign {
|
||||||
-base
|
0 - base
|
||||||
} else {
|
} else {
|
||||||
base
|
base
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user