 01
Jun

Calculate 'time ago' in asp

Now a days we often see websites that show date in the form of "time ago" format e.g "2 Days 12 Hours Ago". Well, that isn't too hard to create its quite easy actually. The basic concept is to get the time difference between two dates and step by step extract different units of time from it. Here is the code

```	Function calculateTimeAgo(theDate)			seconds = DateDiff("s",theDate,Now())				d = int(seconds/86400)		if  d > 0 then			days = d & " days "			seconds = seconds mod 86400		end if																h = int(seconds/3600)		if  h > 0 then			hours = h & " hours "			seconds = seconds mod 3600		end if				mm = int(seconds/60)		if  mm > 0 then			minutes = mm & " mins "			seconds = seconds mod 60		end if				tDiff = days & hours & minutes				if days = "" then			tDiff = tDiff & seconds & " sec"		end if				calculateTimeAgo = tDiff	End Function%>
```

As you can see in the above code, first I've calculated the time difference in Seconds between the time provided and the current time. Then I've divided the seconds into equivalent seconds of 1 day i.e 24x60x60 = 86400 which will give me the no. of days, now obviously remainder won't be zero, we will use the remainder to calculate sequentially the remaining parts as hours, and minutes. For that purpose we are using the function mod to find the remainder and in the next to convert it into hours and then in minutes. After all this convertion we are just putting it together. Thats it folks I hope you find it Useful.

Please Rate, Comment and Share If you liked it.

Feed Subscription

Get daily inboxed with latest news, reviews and tutorials. Signup now it's free :) 