ruby - 在 Ruby 中为 RFC2822 时间强制使用 "+0000"时区

标签 ruby time formatting rfc822 rfc2822

如何强制 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/

相关文章:

ruby - ruby 内部构造的批量分配

python - 如何在python中将小时添加到当前时间

用于单行代码块的 PHP 格式化程序

import - Tslint:最大行长度未由 prettier 修复

python - 如何获取代码在特定 if-elif 构造中花费的时间

html - 如何让 <p> 标签中的两个元素在右侧对齐?

javascript - 我可以从其他页面加载表单吗?

regex - Rails 正则表达式排除符号结束单词之间的空格

Ruby,转换为字符串

objective-c - 如何在Objective-C中更改声音播放开始时间?