views:

33

answers:

3

Wed Sep 22 13:15:02 -0400 2010 to this format 2010-08-23 13:15:02 -0400

The left is Time.now

The right is 30.days.ago =\

+1  A: 

Both are different data types.

>> Time.now.class
=> Time
>> 30.days.ago.class
=> ActiveSupport::TimeWithZone

use the strftime method to format it.

dukz
+1  A: 

You can use the to_s(:db) method in Time class to convert it to a database-friendly format.

Time.now.to_s(:db) # => "2010-09-22 17:50:41"

If you really need the time zone offset info, you could add a custom format to Time::DATE_FORMATS, e.g.

Time::DATE_FORMATS[:db_with_zone_offset] = lambda { |time|
  time.strftime("%Y-%m-%d %H:%M:%S #{time.formatted_offset(false)}")
}

after which you can simply call

Time.now.to_s(:db_with_zone_offset) => # "2010-09-22 17:48:21 +0000"
sluukkonen
I added the custom format (which uses Time#formatted_offset), because as far as I know there is no formatting option in strftime to display the time zone offset (the '+0000'). Rails uses a [similar strategy](http://api.rubyonrails.org/classes/Time.html) in the built-in formatting types. (See especially DATE_FORMATS[:rfc2822])
sluukkonen
+1  A: 

If you want to have format in database format, then you can use:

Time.now
=> Wed Sep 22 19:54:24 +0200 2010
Time.now.to_s(:db)
=> "2010-09-22 19:54:48"
Time.now.utc.to_s(:db)
=> "2010-09-22 17:55:16"
klew