Josh
Josh

Reputation: 3611

Converting twitter post dates to datetime in rails

I am trying to convert the twitter post dates into datetime objects but for some reason they are not converting correctly. If I do this:

d = '12:06 AM Oct 15th'

and

d = DateTime.parse(d)

or

Tweet.new :body => "test", :created_at => d

then the date ends up Sun Nov 15 00:06:00 -0500 2009. All dates are converting and containing the month of November. Am I totally missing something?

Upvotes: 0

Views: 384

Answers (3)

Lukas
Lukas

Reputation: 3235

Always always always use the Chronic gem. Will solve all your problems when it comes to date/time parsing: http://github.com/mojombo/chronic

Upvotes: 1

mtyaka
mtyaka

Reputation: 8848

DateTime.parse expects the passed in string to be in a standard format. Since that is not the case with your strings, you'll have to use DateTime.strptime and pass it your string representation of date/time, along with the corresponding format string. In your case something like this should work:

d = DateTime.strptime '12:06 AM Oct 15th', '%H:%M %p %b %d'

d.to_s  # => "2009-10-15T00:06:00+00:00"

You can check the documentation to see what each of the formatting directions means.

Upvotes: 4

tadman
tadman

Reputation: 211570

You might be able to get away with mangling it slightly and then using the parser:

s = '12:06 AM Oct 15th'

d = DateTime.parse(s.sub(/(\w\w\w) /, '\1'))

puts d.to_s
# => 2009-10-15T00:06:00+00:00

Upvotes: 0

Related Questions