Find Record/Information Time Line

In Rails, we can find the last updated record date/time information with the current date/time information. This can be done as seen below,

def self.didwhen(old_time)
val = Time.now – old_time
if val < 10 then
result = ‘just a moment ago’
elsif val < 40  then
result = ‘less than ‘ + (val * 1.5).to_i.to_s.slice(0,1) + ‘0 seconds ago’
elsif val < 60 then
result = ‘less than a minute ago’
elsif val < 60 * 1.3  then
result = “1 minute ago”
elsif val < 60 * 50  then
result = “#{(val / 60).to_i} minutes ago”
elsif val < 60  * 60  * 1.4 then
result = ‘about 1 hour ago’
elsif val < 60  * 60 * (24 / 1.02) then
result = “about #{(val / 60 / 60 * 1.02).to_i} hours ago”
else
result =old_time.strftime(“%H:%M %p %B %d, %Y”)
end
result
end

By passing the created_dt value to the above function from the rails view section to get printed.The synatax is like,

<% timenow1 = ModelName.didwhen(tablename.created_at)    %>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: