I have this DateTime:
=> Fri, 03 Feb 2012 11:52:42 -0500
How can I remove the zone(-0500) in ruby? I just want something like this:
=> Fri, 03 Feb 2012 11:52:42
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.
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.
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")
PhilT has a great answer, but here's an alternative FOR RAILS. With Rails you can put this into your locale files. Here's an example of specifying various formats.
time:
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
no_timezone: "%a, %d %b %Y %H:%M:%S"
long: "%B %d, %Y %H:%M"
short: "%d %b %H:%M"
time_only: "%I:%M%p"
military_time: "%H:%M"
Then in your code, use I18n.l(DateTime.now, format: :no_timezone)
. You could similarly just set the default format to exclude the timezone.