Skip to content

Commit

Permalink
Add DateTime::fixed_offset
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker authored and djc committed May 15, 2023
1 parent 7bf98de commit eb92784
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/datetime/mod.rs
Expand Up @@ -325,6 +325,14 @@ impl<Tz: TimeZone> DateTime<Tz> {
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<Tz: Timezone>` to `DateTime<FixedOffset>`.
#[inline]
#[must_use]
pub fn fixed_offset(&self) -> DateTime<FixedOffset> {
self.with_timezone(&self.offset().fix())
}

/// Adds given `Duration` to the current date and time.
///
/// Returns `None` when it will result in overflow.
Expand Down
14 changes: 14 additions & 0 deletions src/datetime/tests.rs
Expand Up @@ -1920,4 +1920,18 @@ fn test_datetime_local_from_preserves_offset() {

let datetime_fixed: DateTime<FixedOffset> = 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);
}

0 comments on commit eb92784

Please sign in to comment.