如何强制 Time.rfc2822
函数吐出 +0000
?
Ruby 让我解析 RFC2822格式化时间很容易:
require 'time'
time = Time.parse('14 Aug 2009 09:28:32 +0000')
puts time
=> "2009-08-14 05:28:32 -0400"
但是显示时间呢?请注意,它解析的时间是本地时间。不用担心,我可以使用 gmtime
将它转换回 UTC 时间:
puts time.gmtime
=> "2009-08-14 09:28:32 UTC"
然后我可以将其恢复为 RFC2822 格式:
puts time.gmtime.rfc2822
=> "Fri, 14 Aug 2009 09:28:32 -0000"
不幸的是,这不是我想要的。请注意,+0000
现在是 -0000
。根据 RFC2822,这是因为:
The form "+0000" SHOULD be used to indicate a time zone at Universal Time. Though "-0000" also indicates Universal Time, it is used to indicate that the time was generated on a system that may be in a local time zone other than Universal Time and therefore indicates that the date-time contains no information about the local time zone.
太好了 - 那么除了对 rfc2822
函数进行猴子修补之外,我如何强制执行 +0000
?
最佳答案
这是我的 monkeypatch 解决方案:
class Time
alias_method :old_rfc2822, :rfc2822
def rfc2822
t = old_rfc2822
t.gsub!("-0000", "+0000") if utc?
t
end
end
如果您有非 monkeypatch 解决方案,我很乐意看到它!
关于ruby - 在 Ruby 中为 RFC2822 时间强制使用 "+0000"时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1291274/