将我的 MacOS 升级到最新版本后,Time#strftime 方法出现了一些奇怪的问题。
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'
我当前的 ruby 版本是:
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-darwin16]
我已经试过了:
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin16]
还是不行
我在我 friend 的机器上试过这个(ruby 2.4.1p111(2017-03-22 修订版 58053)[x86_64-darwin15])并且它工作正常。
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'
最佳答案
ruby 中的时区方法完全依赖于 IANA tz database 安装在操作系统中。您在您的计算机和您 friend 的计算机之间观察到的差异仅反射(reflect)了您将 tz 数据库升级到较新版本以及操作系统升级这一事实。
而且,事实上,IANA 正在努力删除一些时区缩写。他们正在删除那些被认为是“发明”的缩写,即由 IANA 工作人员集中命名并且与适本地区的任何实际用法不对应的缩写。另见以下 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.
例如,Kathmandu 的缩写已于 2017 年 1 月专门删除,其中 this commit .
所以,我想你应该坚持 strftime
给你的输出,并实际使用某些时区的数值。
关于ruby-on-rails - Ruby strftime '%Z' 方法返回 '0545' 而不是 'NPT',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43630034/