如何将Rails DateTime对象转换为XML字符串?

时间:2022-10-30 13:49:27

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

我在Rails中有一个DateTime对象,在调用时输出如下:

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:

如何转换DateObject以返回XML日期时间类型字符串,如下所示:

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

4 个解决方案

#1


25  

Time to XML format:

时间到XML格式:

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

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

To parse (Ruby 1.9 and beyond):

要解析(Ruby 1.9及更高版本):

t = Time.now.xmlschema(str)

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

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

#2


5  

Try Time.now.iso8601

试试Time.now.iso8601

#3


1  

Here's a pure-Ruby way:

这是一种纯Ruby方式:

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

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

您可以通过以下方式获得有关各种strftime选项的更多详细信息:

ri Time.strftime

#4


0  

Use the strftime method

使用strftime方法

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

#1


25  

Time to XML format:

时间到XML格式:

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

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

To parse (Ruby 1.9 and beyond):

要解析(Ruby 1.9及更高版本):

t = Time.now.xmlschema(str)

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

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

#2


5  

Try Time.now.iso8601

试试Time.now.iso8601

#3


1  

Here's a pure-Ruby way:

这是一种纯Ruby方式:

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

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

您可以通过以下方式获得有关各种strftime选项的更多详细信息:

ri Time.strftime

#4


0  

Use the strftime method

使用strftime方法

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