views:

71

answers:

2

I am trying to create a stream that includes Twitter data + my app's but I'm having trouble sorting them because their time stamps are formatted in different ways. This is my code:

answers = Answer.find(:all, :conditions => {:user_id => @user_id }, :limit => 20)
tweets = Twitter::Search.new(params[:username]).to_a

@feed = (answers + tweets).sort_by(&:created_at)

these are the formats on time:

<#Hashie::Mash created_at="Tue, 22 Jun 2010 04:41:23 +0000"...
<Answer id:... created_at: "2010-06-15 02:13:40"

Any help would be greatly appreciated.

A: 

Try something like this:

>> dates = []
>> dates << DateTime.now.to_s
=> "2010-06-22T11:49:06-07:00"
>> dates << "2010-06-01"
=> "2010-06-01"
>> dates << "05/05/2015 13:00:00"
=> ["2010-06-22T11:49:34-07:00", "2010-06-01", "05/05/2015 13:00:00"]
>> dates.sort
=> ["05/05/2015 13:00:00", "2010-06-01", "2010-06-22T11:49:34-07:00"]
>> dates.collect {|date| DateTime.parse(date) }.sort
=> [Tue, 01 Jun 2010 00:00:00 +0000, Tue, 22 Jun 2010 11:49:34 -0700, Tue, 05 May 2015 13:00:00 +0000]

Just take this idea and apply it to your application.

Something else I thought of.. try putting this method into each of those classes:

def <=>(other)
  self.created_at <=> other.created_at
end
DJTripleThreat
Thanks, where would the later go in the code? Where in the classes?
Put that method in Hashie::Mash and Answer
DJTripleThreat
+1  A: 

I don't know if this is the best way, but try this:

@feed = (answers + tweets).sort_by{ |x| DateTime.parse("#{x.created_at}") }

Edit

Reverse:

@feed = (answers + tweets).sort{ |x, y| DateTime.parse("#{y.created_at}") <=> DateTime.parse("#{x.created_at}") }
j.
awesome. that works I just need to throw the sorting in reverse. do you know how to do that?
I've edited my answer :]
j.
Awesome. thanks J.
You're welcome, @codyvbrow.
j.