Add `timestamp_millis` method to DateTime and NaiveDateTime

Fixes #151
This commit is contained in:
Brandon W Maister 2017-07-09 15:05:59 -05:00
parent 91d5dd46cf
commit d99304145b
2 changed files with 51 additions and 0 deletions

View File

@ -66,6 +66,30 @@ impl<Tz: TimeZone> DateTime<Tz> {
self.datetime.timestamp() 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 /// Returns the number of milliseconds since the last second boundary
/// ///
/// warning: in event of a leap second, this may exceed 999 /// warning: in event of a leap second, this may exceed 999

View File

@ -263,6 +263,33 @@ impl NaiveDateTime {
(ndays - 719163) * 86400 + nseconds (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. /// Returns the number of milliseconds since the last whole non-leap second.
/// ///
/// The return value ranges from 0 to 999, /// The return value ranges from 0 to 999,