Gre*_*ton 4 ruby ruby-on-rails strftime
我有以下Time对象:
[8] pry(#<#<Class:0x007f928f12f560>>)> display_num
=> 2015-02-19 09:00:00 -0600
[9] pry(#<#<Class:0x007f928f12f560>>)> display_num.is_a?(Time)
=> true
[10] pry(#<#<Class:0x007f928f12f560>>)> display_num.is_a?(DateTime)
=> false
[11] pry(#<#<Class:0x007f928f12f560>>)> display_num.strftime("%l:%M%P %Z")
=> " 9:00am "
[12] pry(#<#<Class:0x007f928f12f560>>)> display_num.strftime("%l:%M%P %z")
=> " 9:00am -0600"
Run Code Online (Sandbox Code Playgroud)
我完全被这样难过:
[16] pry(#<#<Class:0x007f928f12f560>>)> Time.new
=> 2015-02-02 14:09:13 -0800
[17] pry(#<#<Class:0x007f928f12f560>>)> t = Time.new
=> 2015-02-02 14:09:25 -0800
[18] pry(#<#<Class:0x007f928f12f560>>)> t.strftime("%l:%M%P %Z")
=> " 2:09pm PST"
Run Code Online (Sandbox Code Playgroud)
工作得很好.
上面的块中发生了什么,以防止时区以人类可读的格式显示?
format指令%Z请求符号时区(名称或缩写);%z是抵消.虽然您始终知道偏移量,但您可能不知道符号时区名称.
我怀疑这是怎么回事 display_time.它是使用偏移量初始化的,因此它没有任何符号时区名称可供显示.
您也无法可靠地从偏移量中获取名称; 例如,-0400可以是大西洋标准时间或东部夏令时.对于它们所处的时区,大多数偏移将具有多个选项,并且大多数时区无论如何都具有多个名称.
值得补充的是,如果您使用 Rails,ActiveSupport 猴子补丁in_time_zone可用于解决此问题的方法strftime:
Time.current.localtime("-06:00").strftime("TZ is: %Z") # => "TZ is: "
Time.current.in_time_zone("America/Chicago").strftime("TZ is: %Z") # => "TZ is: CDT"
Time.current.in_time_zone("America/New_York").strftime("TZ is: %Z") # => "TZ is: EDT"
Run Code Online (Sandbox Code Playgroud)
参考:
DateAndTime::Zones#in_time_zone
时区字符串的完整列表定义在 ActiveSupport::TimeZone::MAPPING
| 归档时间: |
|
| 查看次数: |
801 次 |
| 最近记录: |