home ~ projects ~ socials

Get A Rust DateTime For A Specific Time Zone

---
[dependencies]
chrono = { version = "0.4.39" }
chrono-tz = { version = "0.10.0" }
---

use chrono::TimeZone;
use chrono_tz::Tz;
use chrono_tz::UTC;

fn main() {
  let tz: Tz = "America/New_York".parse().unwrap();
  let dt_daylight_time = tz.with_ymd_and_hms(2025, 6, 1, 13, 0, 0).unwrap();
  println!("{}", dt_daylight_time.to_rfc2822());
  // let utc = dt_daylight_time.with_timezone(&UTC);
  // println!("{}", utc);
  // let dt_standard_time = tz.with_ymd_and_hms(2025, 12, 1, 13, 0, 0).unwrap();
  // let utc2 = dt_standard_time.with_timezone(&UTC);
  // println!("{}", utc);
}
Output:
Sun, 1 Jun 2025 13:00:00 -0400

warning: unused import: `chrono_tz::UTC`
 --> /Users/alan/.cargo/target/4b/0baba35be9214e/_active_nvim_run:9:5
  |
9 | use chrono_tz::UTC;
  |     ^^^^^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

Notes

  • This handles daylight saving time (compared to FixedOffset which does not being that it's fixed)
-- end of line --

References