Tuesday, 13 April 2010

MVC DateTime Suffix HTMLHelper

Recently I have been working on an MVC Project, and tonight I got to the point where I wanted to output a date in a specific format, for example Tuesday 13th April 2010. Sadly DateTime formatting still doesn't allow you to specify output a suffix, you can do Tuesday 13 April 2010 but not what I wanted.

I decided that I could achieve what I wanted by writing a quick HTMLHelper, this would then allow me to specify a datetime format string with a magic / special character which I could then replace for the appropriate suffix.

Writing the helper was very quick and easy, if you want to learn about HTMLHelpers and how to write your own I recommend looking at Stephen Walther's Post on HTMLHelpers .

The code for my datetimehelper is below:

using System;
using System.Web.Mvc;

namespace mjjames.MVCHelpers
public static class DateTimeExtensions
public static string DateTimeFormat(this HtmlHelper helper, string dateTimeFormat, DateTime dateTime){
var dateTimeOutput = dateTime.ToString(dateTimeFormat);
if (dateTimeFormat.Contains("~"))
dateTimeOutput = dateTimeOutput.Replace("~", GenerateDaySuffix(dateTime.Day));
return dateTimeOutput;

/// <summary>
/// Generates a Day Suffix from the Day Number
/// </summary>
/// <param name="day">Day Number</param>
/// <returns>Suffix String</returns>
private static string GenerateDaySuffix(int day)
var suffix = "";
//find out if the day matches a suffix which isn't th
case 1:
case 21:
case 31:
suffix = "st";
case 2:
case 22:
suffix = "nd";
case 3:
case 23:
suffix = "rd";
suffix = "th";
return suffix;

Then to use it first include the namespace in your view:

<%@ Import Namespace="mjjames.MVCHelpers" %>

And then to use it call Html.DateTimeFormat passing the format string and the DateTime value. To use the day suffix include the ~ character. Note you can use it with.

<%= Html.DateTimeFormat("dddd d~ h", Model.StartDate) %>
<%= Html.DateTimeFormat("dddd d h", Model.EndDate) %>

There we go, nice and easy, if you want to use this feel free I hope it helps

No comments:

Post a Comment