简体   繁体   English

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

[英]How to parse this text into a date format

Can anybody tell me how to parse this text into a date format in rails? 谁能告诉我如何将此文本解析为日期格式的轨道?

Thu Mar 01 11:49:16 +0000 2012 2012年3月1日星期四11:49:16 +0000

From rails console: 从Rails控制台:

[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

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

You can parse it to time. 您可以将其解析为时间。 And then convert to a date. 然后转换为日期。

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

That .to_date answer is the best answer for the question here. 该.to_date答案是此处问题的最佳答案。

But FYI, for other formats, check out the Chronic gem. 但仅供参考,对于其他格式,请查看慢性宝石。

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 https://github.com/mojombo/chronic

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM