'How do you find the local timezone offset in rust

Rust's chrono::Local contains the local timezone information but does not seem to have any methods to get the value as a string or a number of seconds offset.

Any idea's how to get the correct local offset so that

DateTime::parse_from_rfc3339([iso8601 date] + [timezone]).unwrap().with_timezone(&Local)

will return a DateTime that is in the defauilt current timezone of the computer the code is running on.



Solution 1:[1]

You can use

Local.timestamp(0, 0).offset().fix().local_minus_utc()

which returns the local offset to UTC in seconds (eg. it returns 3600 on my CET system).

(Permalink to the playground, which seems to use UTC and hence returns 0)

Solution 2:[2]

You can use the chrono crate and use the following snippet to get the timezone offset.

use chrono::Local;
let offset_in_sec = Local::now()
    .offset()
    .local_minus_utc();
eprintln!("offset: {:?}", offset_in_sec);

If you're using the time crate, then you can use the following snippet to get the timezone offset from offset_in_sec above.

use time::UtcOffset;
let utc_offset_result = UtcOffset::from_whole_seconds(offset_in_sec);
eprintln!("utc_offset_result: {:?}", offset_in_sec);
  1. You can see a real example in r3bl_rs_utils crate here - https://github.com/r3bl-org/r3bl-rs-utils/blob/main/src/utils/file_logging.rs
  2. For more information, you can also checkout: https://developerlife.com/category/Rust/

Solution 3:[3]

For the moment I have a hacky solution that works on Linux only

/// returns local timezone "+01:00"
fn tz() -> String {
    let output = Command::new("date").arg("+%:z").output()
                 .expect("failed to fetch timezone");
    String::from(String::from_utf8_lossy(&output.stdout).trim())
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mcarton
Solution 2 nazmul idris
Solution 3 teknopaul