user841747
user841747

Reputation:

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

Upvotes: 0

Views: 257

Answers (4)

Ryan Porter
Ryan Porter

Reputation: 2182

That .to_date answer is the best answer for the question here.

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

Upvotes: 0

Krule
Krule

Reputation: 6476

From 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

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230551

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

Upvotes: 0

Dorian
Dorian

Reputation: 24009

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

Upvotes: 0

Related Questions