chronotope / chrono-tz

TimeZone implementations for rust-chrono from the IANA database
Other
229 stars 55 forks source link

How to Use DateTime<timezone> with Timezones from crate #88

Closed gluax closed 2 years ago

gluax commented 2 years ago

I want to create a DateTime object from a different Tz, but this doesn't seem possible, or documentation around it seems lacking.

For example, I'd like to be able to do DateTime<GMT>. Or, at the very least, convert a GMT timestamp such as 1636156740 to a DateTime object. Is this possible?

t-cadet commented 2 years ago

I am not sure I fully understand what you are trying to do, but the chrono_tz::Tz type implements the chrono::TimeZone trait which provides methods such as from_local_datetime and from_utc_datetime. You can use the latter to make a DateTime<chrono_tz::Tz> from a DateTime<chrono::Utc>, e.g.

use chrono::{TimeZone, Utc};
use chrono_tz::America;

fn main() {
    let now_nyt = America::New_York.from_utc_datetime(&Utc::now().naive_utc());
}

or documentation around it seems lacking

Maybe you can make a PR to add an example ?

nixpulvis commented 2 years ago

I believe I'm running into the same issue. Basically, I want to specify the actual timezone on the struct (as part of it's type). For example:

struct Entry {
    time: DateTime<Eastern>,
}

Much like how I can type DateTime<Utc>, this should be possible, no?

djc commented 2 years ago

I don't quite see the use case of things like DateTime<Eastern>.

nixpulvis commented 2 years ago

The use case is to statically enforce all uses of the datetime are treated as US eastern times. As I mention, this is exactly the same use case as DateTime<Utc> just following a different Tz. Or am I misunderstanding something?

djc commented 2 years ago

I think the idea in this crate is that we need separate types for things that have a separate mechanism to decide on their offset, but not for things that use the same mechanism but with separate data -- that seems quite reasonable. If you have other needs, it shouldn't be hard to write a newtype wrapper that leverages privacy such that it can only be constructed with Eastern on the inside -- I'm declaring this functionality out of scope for this crate for now.