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
The JavaScript getTimezoneOffset() method is used to find the timezone offset. It returns the timezone difference in minutes, between the UTC and the current local time. If the returned value is positive, local timezone is behind the UTC and if it is negative, the local timezone if ahead of UTC.
To get the current time in particular, you can use the strftime() method and pass into it the string ”%H:%M:%S” representing hours, minutes, and seconds.
When you send the database time to user, convert it to the correct timezone using timeInfo . DateTime userTime = TimeZoneInfo. ConvertTimeFromUtc(dbDateTime, timeInfo);
Construct the value based on UTC, not local times.
let utc = UTC::now().naive_utc();
let dt = Los_Angeles.from_utc_datetime(&utc);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With