diff --git a/CHANGELOG.md b/CHANGELOG.md index b29520ef99..dc3a65642b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,7 @@ Versions with only mechanical changes will be omitted from the following list. * Fix panicking when parsing a `DateTime` (@botahamec) * Add support for getting week bounds based on a specific `NaiveDate` and a `Weekday` (#666) * Remove libc dependency from Cargo.toml. +* Add the `and_local_timezone` method to `NaiveDateTime` ## 0.4.19 diff --git a/src/naive/datetime/mod.rs b/src/naive/datetime/mod.rs index 8b28692c42..e2119e002d 100644 --- a/src/naive/datetime/mod.rs +++ b/src/naive/datetime/mod.rs @@ -21,7 +21,7 @@ use crate::naive::date::{MAX_DATE, MIN_DATE}; use crate::naive::time::{MAX_TIME, MIN_TIME}; use crate::naive::{IsoWeek, NaiveDate, NaiveTime}; use crate::oldtime::Duration as OldDuration; -use crate::{Datelike, Timelike, Weekday}; +use crate::{DateTime, Datelike, LocalResult, TimeZone, Timelike, Weekday}; #[cfg(feature = "rustc-serialize")] pub(super) mod rustc_serialize; @@ -722,6 +722,22 @@ impl NaiveDateTime { pub fn format<'a>(&self, fmt: &'a str) -> DelayedFormat> { self.format_with_items(StrftimeItems::new(fmt)) } + + /// Converts the `NaiveDateTime` into the timezone-aware `DateTime` + /// with the provided timezone, if possible. + /// + /// This is experimental and might be removed in the future. Feel free to + /// let us know what you think about this API. + /// + /// # Example + /// + /// ``` + /// use chrono::{NaiveDate, Utc}; + /// let dt = NaiveDate::from_ymd(2015, 9, 5).and_hms(23, 56, 4).and_local_timezone(Utc).unwrap(); + /// assert_eq!(dt.timezone(), Utc); + pub fn and_local_timezone(&self, tz: Tz) -> LocalResult> { + tz.from_local_datetime(self) + } } impl Datelike for NaiveDateTime { diff --git a/src/naive/datetime/tests.rs b/src/naive/datetime/tests.rs index ea5f91790d..01887332c8 100644 --- a/src/naive/datetime/tests.rs +++ b/src/naive/datetime/tests.rs @@ -1,7 +1,7 @@ use super::NaiveDateTime; use crate::naive::{NaiveDate, MAX_DATE, MIN_DATE}; use crate::oldtime::Duration; -use crate::Datelike; +use crate::{Datelike, FixedOffset, Utc}; use std::i64; #[test] @@ -240,3 +240,16 @@ fn test_nanosecond_range() { NaiveDateTime::from_timestamp(nanos / A_BILLION, (nanos % A_BILLION) as u32) ); } + +#[test] +fn test_and_timezone() { + let ndt = NaiveDate::from_ymd(2022, 6, 15).and_hms(18, 59, 36); + let dt_utc = ndt.and_local_timezone(Utc).unwrap(); + assert_eq!(dt_utc.naive_local(), ndt); + assert_eq!(dt_utc.timezone(), Utc); + + let offset_tz = FixedOffset::west(4 * 3600); + let dt_offset = ndt.and_local_timezone(offset_tz).unwrap(); + assert_eq!(dt_offset.naive_local(), ndt); + assert_eq!(dt_offset.timezone(), offset_tz); +}