Wiring Up TimeAgo and ASPNET MVC

Imagine you want to display something on a page so that instead of raw dates, the user is shown something more relative to the current time.  You’ve probably seen this in some of the applications you use.  “Last Updated: A moment ago” or “about an hour ago”.  There are a variety of ways you can implement this, and it’s been done in many different languages.  In my case, which is an ASP.NET MVC C# application, I considered doing it on the server and simply passing the result as a string to the view for display.  However, in searching for the best way to do this, I stumbled upon the Timeago plugin for jQuery.

image

One of the key benefits of this plugin is that, unlike embedding the strings directly in the HTML, if the user leaves the page open for a while, the relative times remain accurate.  A nice side effect of this is that your pages can still using caching, since they just send the actual datetime of the event’s occurrence, and let Timeago format it into a relative string.  Without this, if you want accurate relative times to be reported, you would need to avoid caching or use micro-caching, since the strings representing the times would rapidly change from “a few seconds ago” to “a minute ago” etc.

Getting set up with Timeago proved to be very simple.  Their home page lists the necessary steps on the client side.  On the server side, all you need to do is send a date in the proper format, which is ISO 8601.  This proved to be slightly challenging to figure out, but once I found the right format setting, it was simple.

The trick is to use a UtcNow and the “o” parameter of .ToString().  For example:

LastActivityDateString=DateTime.UtcNow.ToString("o")

Then, in your view, you can simply output the <abbr> tag like so:

<abbr class="timeago" title="#:LastActivityDateString #">#:LastActivityDateString #</abbr>

(in this case I’m using a Kendo UI Template)

In Razor syntax:

<abbr class="timeago" title="@Model.LastActivityDateString">@Model.LastActivityDateString</abbr>

When you’re done, you’ll be able to display relative times, like these, that update in realtime even after the user has left the web page open for a while.

image

blog comments powered by Disqus