How can I remove the zone from a DateTime value?
When all else fails
zoned_time = Time.now
unzoned_time = Time.new(zoned_time.year, zoned_time.month, zoned_time.day, zoned_time.hour, zoned_time.min, zoned_time.sec, "+00:00")
In addition to the accepted answer you can also add the same strftime
parameters to DATE_FORMATS
a Rails hash allowing you to standardise output formats in your application.
In config/initializers/datetime_formats.rb
:
Time::DATE_FORMATS[:nozone] = '%a, %d %b %Y %H:%M:%S'
Then in your code you could do:
Time.zone.now.to_s(:nozone)
You could even make it the default:
Time::DATE_FORMATS[:default] = '%a, %d %b %Y %H:%M:%S'
Time.zone.now.to_s
There is also a separate hash for dates:
Date::DATE_FORMATS[:default] = '%a, %d %b %Y'
This feature has been around for years but appears to be little known.
Time always has a zone (it has no meaning without one). You can choose to ignore it when printing by using DateTime#strftime
:
now = DateTime.now
puts now
#=> 2012-02-03T10:01:24-07:00
puts now.strftime('%a, %d %b %Y %H:%M:%S')
#=> Fri, 03 Feb 2012 10:01:24
See Time#strftime
for the arcane codes used to construct a particular format.
Alternatively, you may wish to convert your DateTime to UTC for a more general representation.