Hey I would love to know what you think while reading my posts. Please comment!.

Add Ordinal Suffix to formatted DateTime string

This is something which I am sure has bugged you on many occasions, and you always wonder why it isn't built into the .net framework. How to add the Ordinal Suffix to a formatted DateTime string.

There are many examples around the web, but I thought I would just share this one with you while I remember.

Example C#

public static string GetOrdinal(int num)
{
 
    switch (num % 100)
    {
        case 11:
        case 12:
        case 13:
            return num.ToString() + "th";
    }
 
    switch (num % 10)
    {
        case 1:
            return num.ToString() + "st";
        case 2:
            return num.ToString() + "nd";
        case 3:
            return num.ToString() + "rd";
        default:
            return num.ToString() + "th";
    }
 
}

Example VB.Net

Public Function GetOrdinal(num As IntegerAs String
 
    Select Case (num Mod 100)
        Case 11, 12, 13
            Return "th"
    End Select
 
    Select Case (num Mod 10)
        Case 1
            Return "st"
        Case 2
            Return "nd"
        Case 3
            Return "rd"
        Case Else
            Return "th"
    End Select
 
End Function

Example Usage C#

string theDate = string.Format("{0}{1} {2}"DateTime.Now.ToString("dd"), GetOrdinal(DateTime.Now.Day), DateTime.Now.ToString("MMM"));

Example Usage VB.Net

Dim theDate As String = String.Format("{0}{1} {2}", saleDate.ToString("dd"), GetOrdinal(saleDate.Day), saleDate.ToString("MMM"))

About Me

Tim James I'm Tim, a web applications developer from Glasgow, Scotland. Currently working for Kingfisher Systems Ltd, building bespoke systems within the Car Auction industry.

  • C#
  • VB.NET
  • ASP.NET
  • .NET MVC
  • Web API
  • Razor
  • HTML5
  • CSS3
  • jQuery
  • WCF
  • SQL
  • knockout.js
  • Angularjs
  • AJAX
  • APIs
  • SignalR
Why not follow me on twitter? Follow me on Twitter