NullVoxPopuli
NullVoxPopuli

Reputation: 65103

Ruby on Rails: how do I convert this date

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 =\

Upvotes: 0

Views: 131

Answers (3)

sluukkonen
sluukkonen

Reputation: 2616

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"

Upvotes: 2

klew
klew

Reputation: 14967

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"

Upvotes: 1

dukz
dukz

Reputation: 2155

Both are different data types.

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

use the strftime method to format it.

Upvotes: 1

Related Questions