Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change datetime in xml response using Rails3?

I'm using Rails 3.0.4, Ruby 1.9.2p0 on a Mac machine. While using Sqlite as the default database and successfully added respond_to :xml functionality, I see the datetime format in the xml is something like:

<updated-at type="datetime">2011-03-20T12:15:47Z</updated-at>

While there're several posts on the web (also here) asking how to change the date/time format like using configuration in config/locale/en.yml, or add

Time::DATE_FORMATS[:default] = "%Y-%m-%d %H:%M:%S"

in the initializer file, neither work.

I think the problem is because when I call someobj.to_xml, for the datetime objects, rails will call

datetime.xmlschema

instead of calling

datetime.to_s

which bypass the settings mentioned above. Although I know this may be the culprit, I don't know how to fix it. Anyone has experience on this? Thanks a lot!

like image 202
Tyrael Tong Avatar asked Dec 08 '25 09:12

Tyrael Tong


1 Answers

If you absolutely need to change it you can override the xmlschema method instead of the to_s

class DateTime
  def xmlschema
    strftime("%Y-%m-%d %H:%M:%S")
  end
end

But as I said in the comment you are breaking the XLM standard and application connecting to yours will not expect this datetime format.

like image 95
tommasop Avatar answered Dec 10 '25 00:12

tommasop