Format date time in find operation in Rails 3

前端 未结 6 1724
情话喂你
情话喂你 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:47

    Look you use jbuilder? and for example index.json.jbuilder

    json.array!(@textstrings) do |textstring|
      json.extract! textstring, :id, :text
      json.created_at textstring.created_at.to_formatted_s(:short) 
      json.url textstring_url(textstring, format: :json)
    end
    

    in this example I am use method .to_formatted_s

     json.created_at textstring.created_at.to_formatted_s(:short
    

    and i've got

    [{"id":1,"text":"liveasda","created_at":"17 Nov 12:48","url":"http://localhost:5555/textstrings/1.json"},{"id":2,"text":"123","created_at":"17 Nov 14:26","url":"http://localhost:5555/textstrings/2.json"},
    
    0 讨论(0)
  • 2021-01-28 15:49
    Time.now().strftime("%b %d, %Y)
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-28 16:05

    OK, so you want to render the results in JSON formatted nicely. Instead of changing the format of the date on the way in, change it on the way out.

    class Post
    
      def formatted_created_at
        created_at.strftime("%b %d, %Y")
      end
    
      def as_json(args={})
        super(:methods=>:formatted_created_at, :except=>:date)
      end
    end
    
    0 讨论(0)
  • 2021-01-28 16:06

    I would have used Date.parse(datestring) on the client to generate some usable content.

    0 讨论(0)
  • 2021-01-28 16:10

    Off the top of my head, you could do something like:

    @posts = Post.all
    @posts.all.each do |x|
      x.date = x.date.strftime("%b %d, %Y")
    end
    @posts.to_json
    
    0 讨论(0)
提交回复
热议问题