Search code examples
rustrust-chrono

Compare DateTime with fixed offset to DateTime with time zone


How does one convert between DateTime<FixedOffset> and DateTime<Tz>, in order to subtract to get a duration, compare inequality, or reassign?

use chrono::DateTime;
use chrono_tz::America::New_York;

fn main() {
    let mut a = DateTime::parse_from_rfc3339("2022-06- 01T10:00:00").unwrap();
    let b = a.with_timezone(&New_York);
    a = b;
}

An attempt to do this directly yields the error:

error[E0308]: mismatched types
  --> src/main.rs:13:9
   |
11 |     let mut a = DateTime::parse_from_rfc3339("2022-06-01T10:00:00").unwrap();
   |                 ------------------------------------------------------------ expected due to this value
12 |     let b = a.with_timezone(&New_York);
13 |     a = b;
   |         ^ expected struct `FixedOffset`, found enum `Tz`
   |
   = note: expected struct `DateTime<FixedOffset>`
              found struct `DateTime<Tz>`

Playground


Solution

  • Convert the timezone of b into the timezone of a before assigning it:

    a = b.with_timezone(&a.timezone());