如何强制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的说法,这是因为:
表格"+0000“应用于表示”环球时间“时区。虽然"-0000“也表示世界时,但它被用来表示时间是在一个系统上生成的,该系统可能位于一个本地时区而不是通用时间中,因此表示日期-时间不包含有关本地时区的任何信息。
太棒了--那么,除了猴子补丁+0000函数之外,我还能强制使用rfc2822吗?
发布于 2009-08-18 01:28:14
这是我的猴键盘解决方案:
class Time
alias_method :old_rfc2822, :rfc2822
def rfc2822
t = old_rfc2822
t.gsub!("-0000", "+0000") if utc?
t
end
end如果你有一个非猴子的解决方案,我很乐意看到它!
发布于 2017-03-31 08:48:46
最简单的方法如果你不需要在多个地方使用
Time.now.gmtime.rfc2822.sub(/(-)(0+)$/, '+\2')
=> "Fri, 31 Mar 2017 08:39:04 +0000"或作为静态(单例)方法版本。
require 'time'
module MyCustomTimeRFC
def custom_rfc2822(time)
time.gmtime.rfc2822.sub(/(-)(0+)$/, '+\2')
end
module_function :custom_rfc2822
end
t = Time.now
p MyCustomTimeRFC.custom_rfc2822(t)
#=> "Fri, 31 Mar 2017 08:43:15 +0000"或者作为模块扩展,如果您喜欢带有红宝石灵活性的oop风格。
require 'time'
module MyCustomTimeRFC
def custom_rfc2822
gmtime.rfc2822.sub(/(-)(0+)$/, '+\2')
end
end
t = Time.now
t.extend(MyCustomTimeRFC)
p t.custom_rfc2822
#=> "Fri, 31 Mar 2017 08:43:15 +0000"https://stackoverflow.com/questions/1291274
复制相似问题