【问题标题】:Is there a Ruby 1.8.7 time.strftime %z bug?是否有 Ruby 1.8.7 time.strftime %z 错误?
【发布时间】:2012-01-24 00:45:15
【问题描述】:

我遇到了 Ruby 1.8.7 strftime 的问题,其中 %z 在我将时间转换为 UTC 后返回本地时间。

我正在做以下事情:

>> t = Time.now
=> Mon Dec 19 15:20:16 -0800 2011
>> t.strftime("%z")
=> "-0800"

>> t = Time.now.utc
=> Mon Dec 19 23:20:28 UTC 2011
>> t.strftime("%z")
=> "-0800"

即使我将时间更改为 UTC,格式化的时区也会默认为我的本地 PST -0800。

这是一个已知问题吗?有办法解决吗?

【问题讨论】:

    标签: ruby-on-rails ruby timezone ruby-1.8


    【解决方案1】:

    你的问题。

    ruby-1.9.2-p290 :004 > Time.now.strftime("%z")
     => "-0500" 
    ruby-1.9.2-p290 :005 > Time.now.utc.strftime("%z")
     => "+0000" 
    

    【讨论】:

    • OP 的 ruby​​ 版本是 1.8.7,而不是 1.9.2。
    【解决方案2】:

    注意fine 1.8.7 manual 没有提到%z

    ...
    %w - Day of the week (Sunday is 0, 0..6)
    %x - Preferred representation for the date alone, no time
    %X - Preferred representation for the time alone, no date
    %y - Year without a century (00..99)
    %Y - Year with century
    %Z - Time zone name
    %% - Literal ``%'' character
    

    1.9.3 version 确实记录了对%z 的支持:

    Time zone:
      %z - Time zone as hour and minute offset from UTC (e.g. +0900)
              %:z - hour and minute offset from UTC with a colon (e.g. +09:00)
              %::z - hour, minute and second offset from UTC (e.g. +09:00:00)
      %Z - Time zone abbreviation name
    

    %z 产生任何东西的事实似乎是一个未记录的并且可能是意外的实现细节。

    您可以在 1.8.7 和 1.9.3 中使用%Z;例如,您在 1.8.7 中得到这些结果:

    >> t = Time.now
    => Mon Dec 19 16:46:06 -0800 2011
    >> t.zone
    => "PST"
    >> t.strftime('%z %Z')
    => "-0800 PST"
    >> t = Time.now.utc
    => Tue Dec 20 00:46:27 UTC 2011
    >> t.zone
    => "UTC"
    >> t.strftime('%z %Z')
    => "-0800 UTC"
    

    这将为您提供 UTC、PST、EDT 和类似常见缩写的时区。如果你想要偏移量,你应该在1.9.31.8.7 中都使用gmt_offset

    >> Time.now.gmt_offset
    => -28800
    >> Time.now.utc.gmt_offset
    => 0
    

    请注意,gmt_offset 以秒为单位提供偏移量。

    【讨论】:

    • 太棒了。谢谢你的快速反应!现在该程序使用偏移量,所以我们不会太担心它,但很高兴知道偏移量本身不是库的一部分。
    • 在 1.8 中使用 gmt_offset 快速而肮脏地实现“%z”:time = Time.now; "#{time.gmt_offset < 0 ? "-" : "+"}%02d%02d" % (time.gmt_offset/60).abs.divmod(60)
    猜你喜欢
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    相关资源
    最近更新 更多