Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add DateTime::fix_offset #1030

Merged
merged 1 commit into from May 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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);
}