Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

After upgrading my MacOS to latest version, I am having some weird issue 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 ruby version is:

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

I have tried it on:

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

and still not working

I tried this on my friend's machine (ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-darwin15]) and its working fine.

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'
like image 791
Susan Joshi Avatar asked Apr 26 '17 09:04

Susan Joshi


1 Answers

The time zone methods in ruby depend solely on the IANA tz database that is installed in the OS. The difference that you observe between your computer and your friend's computer simply reflects the fact that you had your tz database upgraded to a newer version along with the OS upgrade.

And, indeed, there is an ongoing effort of IANA to remove some of the time zone abbreviations. They are removing those abbreviations that are considered "invented", i.e. named centrally by the IANA crew and not corresponding to any real-world usage in the appropriate localities. See also the following official IANA statement:

Alphabetic time zone abbreviations should not be used as unique identifiers for UTC offsets as they are ambiguous in practice. For example, in English-speaking North America "CST" denotes 6 hours behind UTC, but in China it denotes 8 hours ahead of UTC, and French-speaking North Americans prefer "HNC" to "CST". The tz database contains English abbreviations for many time stamps; unfortunately some of these abbreviations were merely the database maintainers' inventions, and are gradually being removed.

For example, the abbreviation for Kathmandu has been specifically removed in January 2017, with this commit.

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

like image 134
Matouš Borák Avatar answered Sep 20 '22 19:09

Matouš Borák