Getting the current time in specified timezone

4.3k Views Asked by At

Using the Chrono-TZ library, how can I get the current time in a specified time zone?

I tried

let naive_dt = Local::now().naive_local();
let dt = Los_Angeles.from_local_datetime(&naive_dt).unwrap();
println!("{:#?}", dt);

But this printed the datetime in my current timezone, and affixed the requested timezone identifier, thereby giving me a datetime that is off by the difference in timezones.

For example, at 18:30 AEST (UTC+10), I ask for the current time in PST (UTC-8). It should be 00:30 PST. Instead I get 18:30 PST

2

There are 2 best solutions below

0
Synesso On BEST ANSWER

Construct the value based on UTC, not local times.

let utc = UTC::now().naive_utc();
let dt = Los_Angeles.from_utc_datetime(&utc);
0
M. Leonhard On

You can use chrono::DateTime::with_timezone to convert a DateTime<Utc> to another time zone.

Example:

#![forbid(unsafe_code)]
use chrono::{DateTime, Utc};
use chrono_tz::Tz;
use chrono_tz::US::Pacific;

fn main() {
    let pacific_now: DateTime<Tz> = Utc::now().with_timezone(&Pacific);
    println!("pacific_now = {}", pacific_now);
}
$ cargo run --bin example
pacific_now = 2021-07-01 23:22:11.052490 PDT