C# Html String Helper For “a minutes ago”

Sometimes, end-users prefer to see date in “X hours ago” or “X days ago” format. We can easily create an HTML helper class, call the method from any view.

aminutesago

 

public static string TimeAgo(this HtmlHelper html,DateTime dt)
{
    TimeSpan span = DateTime.Now - dt;
    if (span.Days > 365)
    {
        int years = (span.Days / 365);
        if (span.Days % 365 != 0)
            years += 1;
        return String.Format("about {0} {1} ago", 
        years, years == 1 ? "year" : "years");
    }
    if (span.Days > 30)
    {
        int months = (span.Days / 30);
        if (span.Days % 31 != 0)
            months += 1;
        return String.Format("about {0} {1} ago", 
        months, months == 1 ? "month" : "months");
    }
    if (span.Days > 0)
        return String.Format("about {0} {1} ago", 
        span.Days, span.Days == 1 ? "day" : "days");
    if (span.Hours > 0)
        return String.Format("about {0} {1} ago", 
        span.Hours, span.Hours == 1 ? "hour" : "hours");
    if (span.Minutes > 0)
        return String.Format("about {0} {1} ago", 
        span.Minutes, span.Minutes == 1 ? "minute" : "minutes");
    if (span.Seconds > 5)
        return String.Format("about {0} seconds ago", span.Seconds);
    if (span.Seconds <= 5)
        return "just now";
    return string.Empty;
}
@Html.TimeAgo(DateSample)
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