11

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 Answers 2

9

Construct the value based on UTC, not local times.

let utc = UTC::now().naive_utc();
let dt = Los_Angeles.from_utc_datetime(&utc);
5

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.