Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 850
Synesso Avatar asked Dec 15 '16 07:12

Synesso


People also ask

How do I get a specific timezone offset?

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.

How do I get current time zone in Python?

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.

How do I convert datetime to another time zone?

When you send the database time to user, convert it to the correct timezone using timeInfo . DateTime userTime = TimeZoneInfo. ConvertTimeFromUtc(dbDateTime, timeInfo);


2 Answers

Construct the value based on UTC, not local times.

let utc = UTC::now().naive_utc();
let dt = Los_Angeles.from_utc_datetime(&utc);
like image 136
Synesso Avatar answered Nov 02 '22 23:11

Synesso


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
like image 44
M. Leonhard Avatar answered Nov 02 '22 22:11

M. Leonhard