asp.net mvc time ago in words helper

I'm currently using the following extension method. Not sure if it's the best one available out there.

public static string ToRelativeDate(this DateTime dateTime)
{
    var timeSpan = DateTime.Now - dateTime;

    if (timeSpan <= TimeSpan.FromSeconds(60))
        return string.Format("{0} seconds ago", timeSpan.Seconds);

    if (timeSpan <= TimeSpan.FromMinutes(60))
        return timeSpan.Minutes > 1 ? String.Format("about {0} minutes ago", timeSpan.Minutes) : "about a minute ago";

    if (timeSpan <= TimeSpan.FromHours(24))
        return timeSpan.Hours > 1 ? String.Format("about {0} hours ago", timeSpan.Hours) : "about an hour ago";

    if (timeSpan <= TimeSpan.FromDays(30))
        return timeSpan.Days > 1 ? String.Format("about {0} days ago", timeSpan.Days) : "yesterday";

    if (timeSpan <= TimeSpan.FromDays(365))
        return timeSpan.Days > 30 ? String.Format("about {0} months ago", timeSpan.Days / 30) : "about a month ago";

    return timeSpan.Days > 365 ? String.Format("about {0} years ago", timeSpan.Days / 365) : "about a year ago";
}

The helper should be somthing like this:

public MvcHtmlString Timeago(this HtmlHelper helper, DateTime dateTime) 
{
    return MvcHtmlString.Create(dateTime.ToRelativeDate());
}

Hope it helps!


Depending on your intended output target, the jQuery plugin Timeago may be a better option.

Here's an HtmlHelper to create an <abbr /> element containing an ISO 8601 timestamp:

public static MvcHtmlString Timeago(this HtmlHelper helper, DateTime dateTime) {
    var tag = new TagBuilder("abbr");
    tag.AddCssClass("timeago");
    tag.Attributes.Add("title", dateTime.ToString("s") + "Z");
    tag.SetInnerText(dateTime.ToString());

    return MvcHtmlString.Create(tag.ToString());
}

Combine the above helper's output with the following JavaScript somewhere on your page and you'll be in the money.

<script src="jquery.min.js" type="text/javascript"></script>
<script src="jquery.timeago.js" type="text/javascript"></script>

jQuery(document).ready(function() {
  jQuery("abbr.timeago").timeago();
});

Tags:

C#

Asp.Net Mvc