You can convert from a Local DateTime (FixedOffset, or TimeZoned) to UTC like this:
// Construct a Timezone object, we will use it later to build
// some DateTimes, but it is not strictly required for the
// conversion code
let tz_timezone = Tz::from_str(input_string_timezone)
.expect("failed to convert string to chrono tz");
// Create a DateTime::<Utc>
let utc_now = Utc::now();
println!("utc_now: {}", utc_now);
// Create a Local (Timezoned) DateTime
let naive_datetime = utc_now.naive_local();
let london_now = tz_timezone.from_local_datetime(&naive_datetime).unwrap();
println!("london_now: {}", london_now);
// Asside: We can do this another way too
let london_now = chrono_tz::Europe::London.from_local_datetime(&naive_datetime).unwrap();
println!("london_now: {}", london_now);
// The actual conversion code from local timezone time to UTC timezone time
let london_now_utc = Utc.from_utc_datetime(&london_now.naive_utc());
println!("london_now_utc: {}", london_now_utc);
// Bonus: calculate time difference
let difference_from_utc = london_now_utc - utc_now;
println!("difference_from_utc: {}", difference_from_utc);
You can also just use try_from
.
let fixed_offset_datetime: DateTime<chrono::FixedOffset> = ...
let utc_datetime = DateTime::<Utc>::try_from(fixed_offset_datetime)?;