summaryrefslogtreecommitdiff
path: root/src/datetime.rs
diff options
context:
space:
mode:
authorBotahamec <botahamec@outlook.com>2022-03-21 22:00:30 -0400
committerBotahamec <botahamec@outlook.com>2022-03-21 22:00:30 -0400
commitcf2673d4d4bc8d6b96f4488847d8c2b3c3545010 (patch)
treee9777ca24e0f2deda276e4d488e06a5ebeddb5fa /src/datetime.rs
parent54d431b34edcc702ac88ec7d88d42487c12b17b4 (diff)
Add seconds or nanoseconds to DateTime
Diffstat (limited to 'src/datetime.rs')
-rw-r--r--src/datetime.rs32
1 files changed, 31 insertions, 1 deletions
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<Tz: TimeZone> DateTime<Tz> {
}
}
+ pub fn from_local(local_datetime: NaiveDateTime, timezone: Tz) -> Result<Self, Tz::Err> {
+ 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<Tz: TimeZone> DateTime<Tz> {
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<Tz: TimeZone, Other: TimeZone> PartialEq<DateTime<Other>> for DateTime<Tz>
}
impl<Tz: TimeZone> Hash for DateTime<Tz> {
- fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.utc_datetime.hash(state);
}
}