From 7bfa8fb481ebc19c814835067994b5d4ae8683ad Mon Sep 17 00:00:00 2001 From: Pavel Pscheidl Date: Sun, 11 Sep 2022 21:05:51 +0200 Subject: [PATCH] NaiveDateTime::from_timestamp_millis(_opt) Construct NaiveDateTime from millis since epoch. --- src/naive/datetime/mod.rs | 43 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/naive/datetime/mod.rs b/src/naive/datetime/mod.rs index 90f0a08377..1c4a229ba8 100644 --- a/src/naive/datetime/mod.rs +++ b/src/naive/datetime/mod.rs @@ -127,6 +127,49 @@ impl NaiveDateTime { datetime.expect("invalid or out-of-range datetime") } + /// Makes a new `NaiveDateTime` corresponding to a UTC date and time, + /// from the number of milliseconds + /// since the midnight UTC on January 1, 1970 (aka "UNIX timestamp"). + /// + /// Returns `None` on the out-of-range number of milliseconds and/or invalid nanosecond. + /// + /// Panics on the out-of-range number of milliseconds. + /// + /// # Example + /// + /// ``` + /// use chrono::NaiveDateTime; + /// let timestamp_millis: i64 = 1662921288; //Sunday, September 11, 2022 6:34:48 PM + /// let naive_datetime = NaiveDateTime::from_timestamp_millis(timestamp_millis); + /// assert_eq!(timestamp_millis, naive_datetime.timestamp_millis()); + /// ``` + #[inline] + pub fn from_timestamp_millis(millis: i64) -> NaiveDateTime { + NaiveDateTime::from_timestamp_millis_opt(millis).expect("Invalid or out-of-range datetime") + } + + /// Makes a new `NaiveDateTime` corresponding to a UTC date and time, + /// from the number of milliseconds + /// since the midnight UTC on January 1, 1970 (aka "UNIX timestamp"). + /// + /// Returns `None` on the out-of-range number of milliseconds and/or invalid nanosecond. + /// + /// # Example + /// + /// ``` + /// use chrono::NaiveDateTime; + /// let timestamp_millis: i64 = 1662921288; //Sunday, September 11, 2022 6:34:48 PM + /// let naive_datetime = NaiveDateTime::from_timestamp_millis_opt(timestamp_millis); + /// assert!(naive_datetime.is_some()); + /// assert_eq!(timestamp_millis, naive_datetime.unwrap().timestamp_millis()); + /// ``` + #[inline] + pub fn from_timestamp_millis_opt(millis: i64) -> Option { + let secs = millis / 1000; + let nsecs = (millis % 1000) as u32 * 1_000_000; + NaiveDateTime::from_timestamp_opt(secs, nsecs) + } + /// Makes a new `NaiveDateTime` corresponding to a UTC date and time, /// from the number of non-leap seconds /// since the midnight UTC on January 1, 1970 (aka "UNIX timestamp")