2

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

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Test
  • 962
  • 9
  • 26
  • Does this answer your question? [How to convert DateTime to DateTime or vice versa?](https://stackoverflow.com/questions/31186864/how-to-convert-datetimeutc-to-datetimefixedoffset-or-vice-versa) – John Kugelman Jun 25 '22 at 00:11
  • It doesn't, sadly. with_timezone yields a Tz. – Test Jun 25 '22 at 00:13
  • I suppose it's helpful because no one really knows how to convert between these types...they know only how to hack around with autocomplete and google. Why is rust so complicated? When converting between datetimes requires trial-and-error, something has gone very wrong. – Test Jun 25 '22 at 00:15
  • "Why is rust so complicated?" [*Time* is complicated.](https://gist.github.com/timvisee/fcda9bbdff88d45cc9061606b4b923ca) – John Kugelman Jun 25 '22 at 01:35

1 Answers1

1

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

a = b.with_timezone(&a.timezone());
smitop
  • 4,770
  • 2
  • 20
  • 53