13 July 2015

Datetime operations

If you have two DateTime objects, you can determine the difference between them like this:

diff = DateTime.parse('2011-08-29 08:13:00 UTC').to_time - DateTime.parse('2011-08-27 01:00:00 UTC').to_time
# => 198780.0

Once you have the number of seconds, the rest is simply a formatting problem:

'%d:%02d:%02d' % [ diff / 3600, (diff / 60) % 60, diff % 60 ]
# => "55:13:00

Calculate week

def week  
  self.created_at.strftime('%W')
end

Group by week

<% @posts.group_by(&:week).each do |week, posts| %>
  <div id="week">
    <h2>Week < %= week %></h2>
    <%= render :partial => 'post', :collection => @posts %>
  </div>
<% end %>