Time Ago Template for date fields in .Net MVC

I wanted to display dates for certain models in my views like “15 minutes ago.” I tried at first extending the HTML Helper, but I found it easier to just create a template.

@model DateTime
@{
    TimeSpan timeSince = DateTime.Now.Subtract(Model);
}
@if (timeSince.TotalMilliseconds < 1)
  { <text>not yet</text> }
else if (timeSince.TotalMinutes < 1)
  { <text>just now</text> }
else if (timeSince.TotalMinutes < 2)
  { <text>1 minute ago</text> }
else if (timeSince.TotalMinutes < 60)
  { <text>@string.Format("{0} minutes ago", timeSince.Minutes)</text> }
else if (timeSince.TotalMinutes < 120)
  { <text>1 hour ago</text> }
else if (timeSince.TotalHours < 24)
  { <text>@string.Format("{0} hours ago", timeSince.Hours)</text> }
else if (timeSince.TotalDays < 2)
  { <text>yesterday</text> }
else if (timeSince.TotalDays < 7)
  { <text>@string.Format("{0} days ago", timeSince.Days)</text> }
else if (timeSince.TotalDays < 14)
   { <text>"last week</text> }
else if (timeSince.TotalDays < 21)
   { <text>2 weeks ago</text> }
else if (timeSince.TotalDays < 28)
   { <text>3 weeks ago</text> }
else if (timeSince.TotalDays < 60)
   { <text>last month</text> }
else if (timeSince.TotalDays < 365)
   { <text>@string.Format("{0} months ago", Math.Round(timeSince.TotalDays / 30))</text> }
else if (timeSince.TotalDays < 730)
   { <text>last year</text> }
else
   { <text>@string.Format("{0} years ago", Math.Round(timeSince.TotalDays / 365))</text> }

Then I specified the UIHint for the field.

        [UIHint("RelativeDateTime")]
        public DateTime? DateCreated { get; set; }

Then my dates are formated as expected in my views.

  @Html.DisplayFor(modelItem => item.Brand.Name)

Screen shot

MVC in any Application

I was reading in information week about Microsoft’s new MVC framework for .Net. What struck me was that I always associated model-view-controller frameworks with Microsoft. It is a roughly based on a design pattern that I used years ago in developing native Windows applications. It just makes life easier and it is nice to see that Microsoft is now providing it as part of .Net. So what is MVC and how can it be used in almost any application? Read more