如何将此文本解析为日期格式

时间:2012-03-22 13:13:49

标签: ruby-on-rails ruby ruby-on-rails-3 datetime date

有人可以告诉我如何将此文本解析为rails中的日期格式吗?

Thu Mar 01 11:49:16 +0000 2012

4 个答案:

答案 0 :(得分:1)

来自rails console:

[1] pry(main)> "Thu Mar 01 11:49:16 +0000 2012".to_time
=> 2012-03-01 11:49:16 UTC
[2] pry(main)> "Thu Mar 01 11:49:16 +0000 2012".to_date
=> Thu, 01 Mar 2012
[3] pry(main)> "Thu Mar 01 11:49:16 +0000 2012".to_datetime
=> Thu, 01 Mar 2012 11:49:16 +0000

答案 1 :(得分:0)

DateTime.parse("Thu Mar 01 11:49:16 +0000 2012")

答案 2 :(得分:0)

您可以将其解析为时间。然后转换为约会。

require 'active_support/core_ext' # don't need this if on rails.

s = 'Thu Mar 01 11:49:16 +0000 2012'

t = Time.parse s
puts t.to_date

答案 3 :(得分:0)

这个.to_date答案是这里问题的最佳答案。

但是,对于其他格式,仅供参考,查看慢性宝石。

Chronic.parse('tomorrow')
#=> Mon Aug 28 12:00:00 PDT 2006

Chronic.parse('monday', :context => :past)
#=> Mon Aug 21 12:00:00 PDT 2006

Chronic.parse('this tuesday 5:00')
#=> Tue Aug 29 17:00:00 PDT 2006

Chronic.parse('this tuesday 5:00', :ambiguous_time_range => :none)
#=> Tue Aug 29 05:00:00 PDT 2006

Chronic.parse('may 27th', :now => Time.local(2000, 1, 1))
#=> Sat May 27 12:00:00 PDT 2000

Chronic.parse('may 27th', :guess => false)
#=> Sun May 27 00:00:00 PDT 2007..Mon May 28 00:00:00 PDT 2007

https://github.com/mojombo/chronic