diff --git a/src/datetime/mod.rs b/src/datetime/mod.rs index 06d7852e95..940d7b8a35 100644 --- a/src/datetime/mod.rs +++ b/src/datetime/mod.rs @@ -325,6 +325,14 @@ impl DateTime { tz.from_utc_datetime(&self.datetime) } + /// Fix the offset from UTC to its current value, dropping the associated timezone information. + /// This it useful for converting a generic `DateTime` to `DateTime`. + #[inline] + #[must_use] + pub fn fixed_offset(&self) -> DateTime { + self.with_timezone(&self.offset().fix()) + } + /// Adds given `Duration` to the current date and time. /// /// Returns `None` when it will result in overflow. diff --git a/src/datetime/tests.rs b/src/datetime/tests.rs index cf54a76775..ebf0359701 100644 --- a/src/datetime/tests.rs +++ b/src/datetime/tests.rs @@ -1920,4 +1920,18 @@ fn test_datetime_local_from_preserves_offset() { let datetime_fixed: DateTime = datetime.into(); assert_eq!(&offset, datetime_fixed.offset()); + assert_eq!(datetime.fixed_offset(), datetime_fixed); +} + +#[test] +fn test_datetime_fixed_offset() { + let naivedatetime = NaiveDate::from_ymd_opt(2023, 1, 1).unwrap().and_hms_opt(0, 0, 0).unwrap(); + + let datetime = Utc.from_utc_datetime(&naivedatetime); + let fixed_utc = FixedOffset::east_opt(0).unwrap(); + assert_eq!(datetime.fixed_offset(), fixed_utc.from_local_datetime(&naivedatetime).unwrap()); + + let fixed_offset = FixedOffset::east_opt(3600).unwrap(); + let datetime_fixed = fixed_offset.from_local_datetime(&naivedatetime).unwrap(); + assert_eq!(datetime_fixed.fixed_offset(), datetime_fixed); }