开发者

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 Tim开发者_开发知识库e.now

The right is 30.days.ago =\


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"


Both are different data types.

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

use the strftime method to format it.


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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜