How to convert a Rails DateTime object to an XML string?

I have a DateTime object in Rails that is called as follows:

ruby-1.8.7-p302 > Time.now => Wed Nov 10 16:46:51 -0800 2010 

How to convert a DateObject to return a datetime XML type string as follows:

 ruby-1.8.7-p302 > Time.now.convert_to_xml => 2010-11-10T16:46:51-08:00 
+7
xml datetime ruby-on-rails
source share
4 answers

XML time format:

 Time.now.xmlschema # implemented by Rails, not stock ruby Time.now.strftime '%Y-%m-%dT%H:%M:%S%z' 

http://corelib.rubyonrails.org/classes/Time.html#M000281

To analyze (Ruby 1.9 and above):

 t = Time.now.xmlschema(str) 

http://ruby-doc.org/core-1.9/classes/Time.html#M000329

+25
source share

Try Time.now.iso8601

+5
source share

The pure-Ruby method is used here:

 Time.now.strftime("%Y-%m-%dT%H:%M:%S%z") 

You can get more detailed information about the various strftime options with:

 ri Time.strftime 
+1
source share

Use the strftime method

 Time.now.strftime("your format string") 
0
source share

All Articles