From cc613976a4aec87c2bc8b75be71075c2fb34c89b Mon Sep 17 00:00:00 2001 From: Thomas Bytheway Date: Fri, 18 May 2018 11:04:39 +0100 Subject: [PATCH] Add functions to present DateTime in nanoseconds since epoch --- src/datetime.rs | 24 ++++++++++++++++++++++++ src/naive/datetime.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/datetime.rs b/src/datetime.rs index 03d4c3f..00a424f 100644 --- a/src/datetime.rs +++ b/src/datetime.rs @@ -123,6 +123,30 @@ impl DateTime { self.datetime.timestamp_millis() } + /// Returns the number of non-leap-nanoseconds since January 1, 1970 UTC + /// + /// Note that this does reduce the number of years that can be represented + /// from ~584 Billion to ~584. (If this is a problem, please file + /// an issue to let me know what domain needs nanosecond precision over + /// millenia, I'm curious.) + /// + /// # Example + /// + /// ~~~~ + /// use chrono::Utc; + /// use chrono::TimeZone; + /// + /// let dt = Utc.ymd(1970, 1, 1).and_hms_nano(0, 0, 1, 444); + /// assert_eq!(dt.timestamp_nanos(), 1_000_000_444); + /// + /// let dt = Utc.ymd(2001, 9, 9).and_hms_nano(1, 46, 40, 555); + /// assert_eq!(dt.timestamp_nanos(), 1_000_000_000_000_000_555); + /// ~~~~ + #[inline] + pub fn timestamp_nanos(&self) -> i64 { + self.datetime.timestamp_nanos() + } + /// Returns the number of milliseconds since the last second boundary /// /// warning: in event of a leap second, this may exceed 999 diff --git a/src/naive/datetime.rs b/src/naive/datetime.rs index 84d6360..bb3f33f 100644 --- a/src/naive/datetime.rs +++ b/src/naive/datetime.rs @@ -290,6 +290,33 @@ impl NaiveDateTime { as_ms + i64::from(self.timestamp_subsec_millis()) } + /// Returns the number of non-leap *nanoseconds* since midnight on January 1, 1970. + /// + /// Note that this does *not* account for the timezone! + /// The true "UNIX timestamp" would count seconds since the midnight *UTC* on the epoch. + /// + /// Note also that this does reduce the number of years that can be + /// represented from ~584 Billion to ~584. (If this is a problem, + /// please file an issue to let me know what domain needs nanosecond + /// precision over millenia, I'm curious.) + /// + /// # Example + /// + /// ~~~~ + /// use chrono::NaiveDate; + /// + /// let dt = NaiveDate::from_ymd(1970, 1, 1).and_hms_nano(0, 0, 1, 444); + /// assert_eq!(dt.timestamp_nanos(), 1_000_000_444); + /// + /// let dt = NaiveDate::from_ymd(2001, 9, 9).and_hms_nano(1, 46, 40, 555); + /// assert_eq!(dt.timestamp_nanos(), 1_000_000_000_000_000_555); + /// ~~~~ + #[inline] + pub fn timestamp_nanos(&self) -> i64 { + let as_ns = self.timestamp() * 1_000_000_000; + as_ns + i64::from(self.timestamp_subsec_nanos()) + } + /// Returns the number of milliseconds since the last whole non-leap second. /// /// The return value ranges from 0 to 999,