开发者

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 = DateT开发者_如何学JAVAime.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?


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.


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜