Ruby strftime method '% Z' returns '0545' instead of 'NPT'

After updating my MacOS to the latest version, I had some strange problem with the Time # strftime method.

Time.now.in_time_zone("Kathmandu").strftime("%Z") #=> '+0545' Time.now.in_time_zone("Bangkok").strftime("%Z") #=> '+07' Time.now.in_time_zone("Nairobi").strftime("%Z") #=> 'EAT' Time.now.in_time_zone("New Delhi").strftime("%Z") #=> 'IST' 

My current version of ruby:

 ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-darwin16] 

I tried:

 ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin16] 

and still not working

I tried this on my machine for a friend (ruby 2.4.1p111 (version 2017-03-22 version 58053) [x86_64-darwin15]) and its work is excellent.

 Time.now.in_time_zone("Kathmandu").strftime("%Z") #=> 'NPT' Time.now.in_time_zone("Bangkok").strftime("%Z") #=> 'ICT' Time.now.in_time_zone("Nairobi").strftime("%Z") #=> 'EAT' Time.now.in_time_zone("New Delhi").strftime("%Z") #=> 'IST' 
+7
ruby ruby-on-rails macos
source share
2 answers

The time zone methods in ruby ​​depend only on the IANA tz database installed in the OS. The difference that you see between your friend’s computer and your computer simply reflects the fact that your tz database has been updated to a newer version along with an OS update.

And, indeed, there is intensive work by IANA to eliminate some time zone abbreviations. They eliminate those reductions that are considered “invented,” that is, they are called centrally by the IANA crew and do not correspond to actual use in the respective communities. See also the following IANA official report :

Abbreviations with alphabetical time zones should not be used as unique identifiers for UTC offsets, since they are ambiguous in practice. For example, in English-speaking North America, “CST” means 6 hours behind UTC, but in China it means 8 hours earlier than UTC, and French-speaking North Americans prefer “HNC” to “CST”. The tz database contains English abbreviations for many brands of time; Unfortunately, some of these abbreviations were simply inventions of database developers and are gradually being removed .

For example, the abbreviation for Kathmandu was specifically deleted in January 2017, this commit .

So, I think you should stick to the output that strftime gives, and actually use a numeric value for some time zones.

+3
source share

You can create a converter that transfers the numeric time zone offset to the short name. define a hash constant like

 { ... '+0200' => 'CEST', '+0530' => 'IST', ... } 

List completed

0
source share

All Articles