Ordinal Suffix DateTime Extension Method

Posted by William on Aug 4, 2010

In my opinion the most annoying missing piece of date functionality in the .NET framework is an ability to get a DateTime’s ordinal suffix. If you’re as disheartened as me with this then dismay no more. Below is my DateTime extension method that returns the ordinal suffix for the current day of the month.

I’ve put the extension directly into the System namespace, but you can put it somewhere else if you prefer. Now if only we could get this into the frameworks inbuilt date formatting strings, that would be cool!

 
namespace System
{
        ///<summary>
        ///Returns the ordinal suffix for the day of the month represented by this instance
        ///</summary>
        ///<returns></returns>
        public static string OrdinalSuffix(this DateTime datetime)
        {
            int day = datetime.Day;
 
            if (day % 100 >= 11 && day % 100 <= 13)
                return String.Concat(day, "th");
 
            switch (day % 10)
            {
                case 1:
                    return String.Concat(day, "st");
                case 2:
                    return String.Concat(day, "nd");
                case 3:
                    return String.Concat(day, "rd");
                default:
                    return String.Concat(day, "th");
            }
        }
}