Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing "+0000" timezone for RFC2822 times in Ruby

How can I force the Time.rfc2822 function to spit out +0000?

Ruby lets me parse RFC2822 formatted times pretty easily:

require 'time'
time = Time.parse('14 Aug 2009 09:28:32 +0000')
puts time
=> "2009-08-14 05:28:32 -0400"

But what about displaying times? Notice that the time it parsed is a local time. No worries, I can convert it back to a UTC time with gmtime:

puts time.gmtime
=> "2009-08-14 09:28:32 UTC"

I can then put it back into RFC2822 format:

puts time.gmtime.rfc2822
=> "Fri, 14 Aug 2009 09:28:32 -0000"

Unfortunately, this is not quite what I want. Notice that the +0000 is now -0000. According to RFC2822, this is because:

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.

Great - so how can I force +0000 other than monkey-patching the rfc2822 function?

like image 663
Bkkbrad Avatar asked Oct 14 '22 14:10

Bkkbrad


1 Answers

Here's my monkeypatch solution:

class Time
  alias_method :old_rfc2822, :rfc2822
  def rfc2822
    t = old_rfc2822
    t.gsub!("-0000", "+0000") if utc?
    t
  end
end

If you have a non-monkeypatch solution, I would love to see it!

like image 59
Bkkbrad Avatar answered Oct 20 '22 06:10

Bkkbrad