From d99304145b7c3d183ff5355e71a080d3a9b91712 Mon Sep 17 00:00:00 2001 From: Brandon W Maister Date: Sun, 9 Jul 2017 15:05:59 -0500 Subject: [PATCH] Add `timestamp_millis` method to DateTime and NaiveDateTime Fixes #151 --- 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 9c440e8..d8493fb 100644 --- a/src/datetime.rs +++ b/src/datetime.rs @@ -66,6 +66,30 @@ impl DateTime { self.datetime.timestamp() } + /// Returns the number of non-leap-milliseconds since January 1, 1970 UTC + /// + /// Note that this does reduce the number of years that can be represented + /// from ~584 Billion to ~584 Million. (If this is a problem, please file + /// an issue to let me know what domain needs millisecond precision over + /// billions of years, I'm curious.) + /// + /// # Example + /// + /// ~~~~ + /// use chrono::Utc; + /// use chrono::TimeZone; + /// + /// let dt = Utc.ymd(1970, 1, 1).and_hms_milli(0, 0, 1, 444); + /// assert_eq!(dt.timestamp_millis(), 1_444); + /// + /// let dt = Utc.ymd(2001, 9, 9).and_hms_milli(1, 46, 40, 555); + /// assert_eq!(dt.timestamp_millis(), 1_000_000_000_555); + /// ~~~~ + #[inline] + pub fn timestamp_millis(&self) -> i64 { + self.datetime.timestamp_millis() + } + /// 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 cf976e6..d6f3eae 100644 --- a/src/naive/datetime.rs +++ b/src/naive/datetime.rs @@ -263,6 +263,33 @@ impl NaiveDateTime { (ndays - 719163) * 86400 + nseconds } + /// Returns the number of non-leap *milliseconds* 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 Million. (If this is a problem, + /// please file an issue to let me know what domain needs millisecond + /// precision over billions of years, I'm curious.) + /// + /// # Example + /// + /// ~~~~ + /// use chrono::NaiveDate; + /// + /// let dt = NaiveDate::from_ymd(1970, 1, 1).and_hms_milli(0, 0, 1, 444); + /// assert_eq!(dt.timestamp_millis(), 1_444); + /// + /// let dt = NaiveDate::from_ymd(2001, 9, 9).and_hms_milli(1, 46, 40, 555); + /// assert_eq!(dt.timestamp_millis(), 1_000_000_000_555); + /// ~~~~ + #[inline] + pub fn timestamp_millis(&self) -> i64 { + let as_ms = self.timestamp() * 1000; + as_ms + self.timestamp_subsec_millis() as i64 + } + /// Returns the number of milliseconds since the last whole non-leap second. /// /// The return value ranges from 0 to 999,