[英]strftime %Z behaves differently on Time and DateTime
>> Time.now.strftime("%Z")
=> "CST"
>> DateTime.now.strftime("%Z")
=> "+08:00"
>> DateTime.new(2017, 2, 1, 17, 30, 0, "PST").strftime("%Z")
=> "-08:00"
So I want to print out the timezone name so I reached to strftime
. 所以我想打印出时区名称,以便到达
strftime
。 However it behaves differently if I give a DateTime to it. 但是,如果我给它一个DateTime,它的行为会有所不同。 Why is this the case?
为什么会这样呢? Does that mean I can't use DateTime.new to initialize an arbitrary time of a specific timezone?
这是否意味着我无法使用DateTime.new初始化特定时区的任意时间?
You can set the time zone of a DateTime
with in_time_zone
: 您可以使用
in_time_zone
设置DateTime
的时区:
DateTime.now.in_time_zone("Pacific Time (US & Canada)").strftime("%Z")
Time
will automatically include a time zone if specified. 如果指定了时间,
Time
将自动包括一个时区。
I've run into the same issue. 我遇到了同样的问题。 This appears to be the cause:
这似乎是原因:
Time
knows its time zone (and we can derive the offset from that) Time
知道其时区(我们可以从中得出偏移量) DateTime
only knows its offset from UTC (which might be more than one time zone, because of inconsistent observance of Daylight Savings Time) DateTime
仅知道其与UTC的偏移量(由于不遵守夏令时,可能会超过一个时区) For example, right now both Phoenix, Arizona and San Francisco, CA are the same offset from UTC (-0700), but different time zones (MST, and PDT, respectively). 例如,现在亚利桑那州凤凰城和加利福尼亚州旧金山的UTC偏移时间相同(-0700),但时区不同(分别为MST和PDT)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.