home ~ projects ~ socials

Convert A NaiveDate Time To A DateTime With A Specific TimeZone In Rust With chrono

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

use chrono::NaiveDate;
use chrono_tz::Tz;

fn main() {

  let tz: Tz = "America/New_York".parse().unwrap();

  let standard_time_example = NaiveDate::from_ymd_opt(2025, 1, 1)
    .unwrap()
    .and_hms_opt(12, 0, 0)
    .unwrap()
    .and_local_timezone(tz)
    .unwrap();

  let daylight_time_example = NaiveDate::from_ymd_opt(2025, 6, 1)
    .unwrap()
    .and_hms_opt(12, 0, 0)
    .unwrap()
    .and_local_timezone(tz)
    .unwrap();

  println!("{}", standard_time_example);
  println!("{}", standard_time_example.to_utc());
  println!("{}", daylight_time_example);
  println!("{}", daylight_time_example.to_utc());
}
Output:
2025-01-01 12:00:00 EST
2025-01-01 17:00:00 UTC
2025-06-01 12:00:00 EDT
2025-06-01 16:00:00 UTC
-- end of line --