Skip to content

Commit

Permalink
NaiveDateTime::from_timestamp_millis(_opt)
Browse files Browse the repository at this point in the history
Construct NaiveDateTime from millis since epoch.
  • Loading branch information
Pscheidl committed Sep 11, 2022
1 parent 5305023 commit 7bfa8fb
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/naive/datetime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<NaiveDateTime> {
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")
Expand Down

0 comments on commit 7bfa8fb

Please sign in to comment.