1

I have a timezone name, like "America/New_York" and the year, month, day, hour, minute and second in that timezone, for a particular time. How can I get a timezone aware DateTime object for that time in that timezone. Like a Local object, but with the specified timezone instead of the local timezone.

std::env::set_var("TZ", "America/New_York");
let x = Local.ymd(2019, 12, 1).and_hms(2, 0, 0);

This gives the result that I want, but I don't want to be setting the TZ environment variable because I want Local to remain local time and I need to be able to change the TZ for different cases while chrono only reads the TZ environment variable once, as far as I know.

What I want is something like

let x = ???.tz("America/New_York").ymd(2019, 12, 1).and_hms(2, 0, 0);

That returns a timezone aware DateTime that will handle operations like adding and subtracting durations correctly, given the timezone. So a FixeOffest doesn't work because adding a duration that spans a daylight savings time transition, for example, doesn't (in my experience) yield a result with the correct offset - it stays at the original fixed offset even though that doesn't apply at the new date.

Is there such a thing? Can I make a Local object with a specified TZ without setting the TZ environment variable?

Ian
  • 2,078
  • 2
  • 19
  • 19
  • Does the `chrono-tz` crate do what you want? – Raj Jan 09 '20 at 21:57
  • It may but the context is code that is already heavily committed to rust-chrono, so I would prefer not to introduce another create. – Ian Jan 09 '20 at 22:33
  • Please take a look at chrono-tz. I believe it _is_ what you need. It's an extension to chrono with concrete timezone information. – Sven Marnach Jan 09 '20 at 22:45
  • Thank you. Actually that does look like what I want. Somehow I had misunderstood that it was an alternative time library with TZ, rather than an extension to chrono. I'll see if I can do what I want with it. – Ian Jan 10 '20 at 23:36

1 Answers1

0

You can simply use chrono_tz

use chrono::TimeZone;
use chrono_tz::Tz;
fn main() {
    let x = chrono_tz::America::New_York.with_ymd_and_hms(2019, 12, 1, 2, 0, 0);
    // or with parsing from a string:
    let y = "America/New_York"
        .parse::<Tz>()
        .unwrap()
        .with_ymd_and_hms(2022, 12, 1, 1, 39, 0);
    dbg!(x, y);
}
cafce25
  • 15,907
  • 4
  • 25
  • 31