10

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

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Synesso
  • 37,610
  • 35
  • 136
  • 207

2 Answers2

9

Construct the value based on UTC, not local times.

let utc = UTC::now().naive_utc();
let dt = Los_Angeles.from_utc_datetime(&utc);
Synesso
  • 37,610
  • 35
  • 136
  • 207
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
M. Leonhard
  • 1,332
  • 1
  • 18
  • 20