From 505db4504d334f21c14e1591bad49ca228a05ab0 Mon Sep 17 00:00:00 2001 From: Brandon W Maister Date: Wed, 18 Sep 2019 17:48:39 -0400 Subject: [PATCH] Add Datelike::num_days_from_epoch --- src/lib.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index b43fa0d..0c0d7ea 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -454,6 +454,8 @@ macro_rules! try_opt { ($e:expr) => (match $e { Some(v) => v, None => return None }) } +const EPOCH_NUM_DAYS_FROM_CE: i32 = 719_163; + mod div; #[cfg(not(feature="clock"))] mod oldtime; @@ -895,6 +897,7 @@ pub trait Datelike: Sized { /// /// ~~~ /// use chrono::{NaiveDate, Datelike}; + /// /// assert_eq!(NaiveDate::from_ymd(1970, 1, 1).num_days_from_ce(), 719163); /// assert_eq!(NaiveDate::from_ymd(0, 1, 1).num_days_from_ce(), -365); /// ~~~ @@ -911,6 +914,21 @@ pub trait Datelike: Sized { ndays += ((year * 1461) >> 2) - div_100 + (div_100 >> 2); ndays + self.ordinal() as i32 } + + /// Return the number of days since the unix epoch, 1970-01-01 + /// + /// # Example: + /// + /// ``` + /// use chrono::{NaiveDate, Datelike}; + /// + /// assert_eq!(NaiveDate::from_ymd(1970, 1, 1).num_days_from_epoch(), 0); + /// assert_eq!(NaiveDate::from_ymd(1969, 1, 1).num_days_from_epoch(), -365); + /// assert_eq!(NaiveDate::from_ymd(1999, 12, 31).num_days_from_epoch(), 10_956); + /// ``` + fn num_days_from_epoch(&self) -> i32 { + self.num_days_from_ce() - EPOCH_NUM_DAYS_FROM_CE + } } /// The common set of methods for time component.