rustrust-chronochrono-tz

Getting the current time in specified timezone


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


Solution

  • Construct the value based on the UTC timezone, not the local (system) timezone.

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