I\'m writing a Rails application, but can\'t seem to find how to do relative time, i.e. if given a certain Time class, it can calculate \"30 seconds ago\" or \"2 days ago\"
Another approach is to unload some logic from the backend and maek the browser do the job by using Javascript plugins such as:
jQuery time ago or its Rails Gem adaptation
Since the most answer here suggests time_ago_in_words.
Instead of using :
<%= time_ago_in_words(comment.created_at) %>
In Rails, prefer:
<abbr class="timeago" title="<%= comment.created_at.getutc.iso8601 %>">
<%= comment.created_at.to_s %>
</abbr>
along with a jQuery library http://timeago.yarp.com/, with code:
$("abbr.timeago").timeago();
Main advantage: caching
http://rails-bestpractices.com/posts/2012/02/10/not-use-time_ago_in_words/
If you're building a Rails application, you should use
Time.zone.now
Time.zone.today
Time.zone.yesterday
This gives you time or date in the timezone with which you've configured your Rails application.
For example, if you configure your application to use UTC, then Time.zone.now
will always be in UTC time (it won't be impacted by the change of British Summertime for example).
Calculating relative time is easy, eg
Time.zone.now - 10.minute
Time.zone.today.days_ago(5)
Take a look at the instance methods here:
http://apidock.com/rails/Time
This has useful methods such as yesterday, tomorrow, beginning_of_week, ago, etc.
Examples:
Time.now.yesterday
Time.now.ago(2.days).end_of_day
Time.now.next_month.beginning_of_month
Something like this would work.
def relative_time(start_time)
diff_seconds = Time.now - start_time
case diff_seconds
when 0 .. 59
puts "#{diff_seconds} seconds ago"
when 60 .. (3600-1)
puts "#{diff_seconds/60} minutes ago"
when 3600 .. (3600*24-1)
puts "#{diff_seconds/3600} hours ago"
when (3600*24) .. (3600*24*30)
puts "#{diff_seconds/(3600*24)} days ago"
else
puts start_time.strftime("%m/%d/%Y")
end
end
Sounds like you're looking for the time_ago_in_words method (or distance_of_time_in_words), from ActiveSupport. Call it like this:
<%= time_ago_in_words(timestamp) %>