Finding corresponding timezone for fixed offset location

Hey,

I am parsing a date that contains a timezone like -05:00 at the end. Parsing this will end up with a fixed location. Is there any possibility to look this up, so that printing out that date using the %^Z date time formatter would show me an identifier like EST again - despite this being ambiguous?

Any chance of looking up time zones like that?

Thanks a ton!

–Alex

This feels like a bug:

string = "2021-10-02T10:00:00-05:00"
 
time = Time.parse_rfc3339 string
 
pp time # => 2021-10-02 10:00:00.0 -05:00
 
puts time.to_s "%F %^Z" # => 2021-10-02 -05:00

Based on the Time::Format docs I’d have expected it to be EST as you mention as %:z is the one that should output this type of offset.

It’s complicated[tm] as EST is not the only timezone matching -05:00, so why should EST be the first choice - unless I am missing some standard that defines the correct order within the timezone database. Haven’t dug that deep yet.

Oh I guess I didn’t look into it that much either. I always kinda just assumed the abbreviations were standardized, but apparently not…

As you already mentioned, going from a UTC offset to a zone identifier is ambiguous. So this really can’t be done automatically.
You could certainly implement some lookup rules to your liking.

string = "2021-10-02T10:00:00-05:00"
 
time = Time.parse_rfc3339 string

if time.offset == -5 * 3600
  time = time.in(Time::Location.load("EST"))
end
 
p! time.to_s("%F %^Z") # => "2021-10-02 EST"

But… I’d say this is a pretty bad idea in general. It can only break. Time zones are complex and if you’re missing time zone information, you’re simply missing it. It effectively can’t be reconstructed from partial data.

Hey,

so, turns out I got lucky, and the Bevy API I am consuming also sends a timezone field that contains something like America/Los_Angeles - with that I can load the correct time zone via Time::Location.load() as you showed above and not as bad as if I would implement a half correct solution myself.

Thanks for all your input, much appreciated!

–Alex