Format date time in find operation in Rails 3

前端 未结 6 1723
情话喂你
情话喂你 2021-01-28 15:34

I\'m looking for a way to format date time in find(:all) so that when I render my results in JSON, the date time will look like

\"March 20, 2011\"

instead of

6条回答
  •  清酒与你
    2021-01-28 15:52

    That works (checked in Rails 3.1), put it into config/initializer/times_format.js. First two lines fix default time format (e.g. AR created_at). Third part is monkey patch for JSON.

    Date::DATE_FORMATS[:default] = "%Y-%m-%d"
    Time::DATE_FORMATS[:default] = "%Y-%m-%d %H:%M:%S"
    
    class ActiveSupport::TimeWithZone
      def as_json(options={})
        strftime('%Y-%m-%d %H:%M:%S')
      end
    end
    

提交回复
热议问题