Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc time ago in words helper [duplicate]

Tags:

c#

asp.net-mvc

Possible Duplicate:
How do I calculate relative time?

Is there anything similar to rails' time_ago_in_words helper for asp.net MVC?

like image 731
ryudice Avatar asked Mar 14 '11 16:03

ryudice


2 Answers

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();
});
like image 98
Nathan Taylor Avatar answered Oct 22 '22 03:10

Nathan Taylor


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!

like image 24
goenning Avatar answered Oct 22 '22 03:10

goenning