简体   繁体   English

是否存在Ruby 1.8.7 time.strftime%z错误?

[英]Is there a Ruby 1.8.7 time.strftime %z bug?

I'm having an issue with Ruby 1.8.7 strftime where the %z is returning the local time after i convert the time to UTC. 我在Ruby 1.8.7 strftime时遇到问题,在将时间转换为UTC之后,%z返回本地时间。

I'm doing the following: 我正在执行以下操作:

>> 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"

Even after I change the time to UTC, the timezone formatted gets defaulted to my local PST -0800. 即使我将时间更改为UTC,格式化的时区仍默认为我的本地PST -0800。

Is this a known issue? 这是一个已知的问题? Is there a way around it? 有办法解决吗?

Note that the fine 1.8.7 manual makes no mention of %z : 请注意, 精美的1.8.7手册没有提到%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

but the 1.9.3 version does have documented support for %z : 但是1.9.3版本确实记录了对%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

The fact the %z produces anything at all appears to be an undocumented and possibly accidental implementation detail. %z根本不产生任何结果的事实似乎是未记录的,可能是偶然的实现细节。

You can use %Z in 1.8.7 and 1.9.3; 您可以在1.8.7和1.9.3中使用%Z for example, you get these results in 1.8.7: 例如,您在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"

That will give you the timezone as UTC, PST, EDT, and similar common abbreviations. 这将为您提供时区,如UTC,PST,EDT以及类似的常见缩写。 If you want the offset, you should be using gmt_offset in both 1.9.3 and 1.8.7 : 如果需要偏移量,则应该在1.9.31.8.7中都使用gmt_offset

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

Note that gmt_offset gives you the offset in seconds. 请注意, gmt_offset以秒为单位提供偏移量。

Your problem. 你的问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM