Extend Date to get an ordinal suffix

  • January 13, 2016
  • C#

Added a simple extension to the Date object as to output an ordinal suffix.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace StuartsPlayground.App_Code
{
public static class DateTimeExtensions
{
public static string ToStringWithOrdinal(this DateTime d)
{
var result = "";
bool gotOne = false;

switch ( d.Day % 100 )
{
case 11:
case 12:
case 13:
result = "th";
gotOne = true;
break;
}

if ( !gotOne )
{
switch ( d.Day % 10 )
{
case 1:
result = "st";
break;
case 2:
result = "nd";
break;
case 3:
result = "rd";
break;
default:
result = "th";
break;
}
}

return String.Format(d.ToString("d{0} MMMM yyyy"), result);

}
}
}




No Comments


No comments yet.



Leave a Reply

Your email address will not be published. Required fields are marked *