I have two DateTime
objects of different type which I would like to be able to subtract, or otherwise find the Duration
difference between.
Here is some example code:
// First step: Want to be able to construct DateTimes for a set of different
// timezones.
//
// To do this, we first create a Utc now object, and convert it to different
// timezones, as required. For example here, we convert to London.
let utc_now = Utc::now();
let naive_utc_datetime = utc_now.naive_local();
// Since this time is in Utc, `naive_local` should return the same as
// `naive_utc` ?
// Create London time from a chrono_tz Timezone
let london_now = chrono_tz::Europe::London.from_utc_datetime(&naive_utc_datetime);
println!("london_now: {}", london_now);
// london_now: 2023-08-31 10:07:43.421198168 BST
let difference_from_utc = london_now - utc_now;
println!("difference_from_utc: {}", difference_from_utc);
// does not compile
The final line does not compile, this is why:
cannot subtract `DateTime<Utc>` from `DateTime<Tz>`
the trait `Sub<DateTime<Utc>>` is not implemented for `DateTime<Tz>`
the following other types implement trait `Sub<Rhs>`:
<DateTime<Tz> as Sub<Days>>
<DateTime<Tz> as Sub<FixedOffset>>
<DateTime<Tz> as Sub<Months>>
<DateTime<Tz> as Sub<chrono::Duration>>
<DateTime<Tz> as Sub>
The question is, how can we obtain the Duration
(or otherwise) difference between the time in London and the Utc time. Since it is currently British Summer Time, I would expect to see a difference of exactly 1 hour on todays date. (2023-08-31)
Related: The following question explains how to subtract two DateTime::<T>
objects assuming they have the same type T
.
This will work if both datetimes are DateTime::<Utc>
but not otherwise.