Chanpory
Chanpory

Reputation: 3095

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

I have a DateTime object in Rails which outputs like this when called:

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

How do I convert the DateObject to return an XML datetime type string like this:

ruby-1.8.7-p302 > Time.now.convert_to_xml
 => 2010-11-10T16:46:51-08:00

Upvotes: 7

Views: 4404

Answers (4)

Fábio Batista
Fábio Batista

Reputation: 25280

Time to XML 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 parse (Ruby 1.9 and beyond):

t = Time.now.xmlschema(str)

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

Upvotes: 25

rwilliams
rwilliams

Reputation: 21497

Use the strftime method

Time.now.strftime("your format string")

Upvotes: 0

trptcolin
trptcolin

Reputation: 2340

Here's a pure-Ruby way:

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

You can get more details about the various strftime options with:

ri Time.strftime

Upvotes: 1

William
William

Reputation: 3529

Try Time.now.iso8601

Upvotes: 6

Related Questions