Add from_timestamp_millis to DateTime<Utc> (#1374)

Co-authored-by: xmakro <makro@>
This commit is contained in:
Makro 2024-01-10 00:50:58 +08:00 committed by GitHub
parent 65f0cc2aa4
commit 6ec8f97d16
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 0 deletions

View File

@ -624,6 +624,34 @@ impl DateTime<Utc> {
NaiveDateTime::from_timestamp_opt(secs, nsecs).as_ref().map(NaiveDateTime::and_utc)
}
/// Makes a new [`DateTime<Utc>`] from the number of non-leap milliseconds
/// since January 1, 1970 0:00:00.000 UTC (aka "UNIX timestamp").
///
/// This is guaranteed to round-trip with regard to [`timestamp_millis`](DateTime::timestamp_millis).
///
/// If you need to create a `DateTime` with a [`TimeZone`] different from [`Utc`], use
/// [`TimeZone::timestamp_millis_opt`] or [`DateTime::with_timezone`].
///
/// # Errors
///
/// Returns `None` on out-of-range number of milliseconds, otherwise returns `Some(DateTime {...})`.
///
/// # Example
///
/// ```
/// use chrono::{DateTime, Utc};
///
/// let dt: DateTime<Utc> = DateTime::<Utc>::from_timestamp_millis(947638923004).expect("invalid timestamp");
///
/// assert_eq!(dt.to_string(), "2000-01-12 01:02:03.004 UTC");
/// assert_eq!(DateTime::from_timestamp_millis(dt.timestamp_millis()).unwrap(), dt);
/// ```
#[inline]
#[must_use]
pub fn from_timestamp_millis(millis: i64) -> Option<Self> {
NaiveDateTime::from_timestamp_millis(millis).as_ref().map(NaiveDateTime::and_utc)
}
// FIXME: remove when our MSRV is 1.61+
// This method is used by `NaiveDateTime::and_utc` because `DateTime::from_naive_utc_and_offset`
// can't be made const yet.

View File

@ -1253,6 +1253,18 @@ fn test_datetime_from_local() {
assert_eq!(datetime_west, datetime_utc.with_timezone(&timezone_west));
}
#[test]
fn test_datetime_from_timestamp_millis() {
// 2000-01-12T01:02:03:004Z
let naive_dt =
NaiveDate::from_ymd_opt(2000, 1, 12).unwrap().and_hms_milli_opt(1, 2, 3, 4).unwrap();
let datetime_utc = DateTime::<Utc>::from_naive_utc_and_offset(naive_dt, Utc);
assert_eq!(
datetime_utc,
DateTime::<Utc>::from_timestamp_millis(datetime_utc.timestamp_millis()).unwrap()
);
}
#[test]
#[cfg(feature = "clock")]
fn test_years_elapsed() {