Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract time zone identifier from DateTime instance

I'm looking for a way to extract friendly zone identifier (like CET, GMT or UTC) from a DateTime instance.

A few of my failed attempts:

>> DateTime.current.zone
=> "+00:00" # Not what I want

>> Time.current.zone
=> "UTC"
>> DateTime.current.to_time.zone
=> "CET" # Uses system time instead of the one set in Rails config

I also managed to find that if you cast DateTime instance to a specific zone, DateTime#zone returns the abbreviation I'm looking for, but that doesn't work for uncast instance:

>> DateTime.current.in_time_zone('America/Los_Angeles').zone
=> "PDT"
>> DateTime.current.zone
=> "+00:00
like image 451
Rafał Cieślak Avatar asked Aug 15 '26 23:08

Rafał Cieślak


1 Answers

Another one to try: Time.now.zone

Other time related goodies:

  • Rails api docs for Time
  • Thoughtbot timezone article
like image 197
Jeff Spicoli Avatar answered Aug 18 '26 16:08

Jeff Spicoli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!