Smit Shah

Ordinals in .Net

We have all come across projects where we have to display the date, but not just the date, also the ordinal that goes with the date.

Example:July 31st 2012, 10:27 AM

The standard .Net library only offers a July 31 2012, 10:27 AM without the "st"

To achive this, simply create a function and use it in your code.

    '[String].Format("{0:dddd}, {1} {0:MMMM} {0:yyyy}", [date], AppendDaySuffix([date].Day))
    Public Function AppendDaySuffix(day As Integer) As String
        Dim daySuffix As String = ""
        If day = 1 OrElse day = 21 OrElse day = 31 Then
            daySuffix = "st"
        ElseIf day = 2 OrElse day = 22 Then
            daySuffix = "nd"
        ElseIf day = 3 OrElse day = 23 Then
            daySuffix = "rd"
        Else
            daySuffix = "th"
        End If
        Return (day & daySuffix)
    End Function


And wherever you are trying to print the output to, simply use 
<%=String.Format("{0:MMMM} {1} {0:yyyy}, {0:hh}:{0:mm} {0:tt}",Now, AppendDaySuffix(Now.Day))%>


I hope this helps you save time searching for a solution.

Please provide your feedback.
                                                                                         
This is a personal weblog. The opinions expressed here represent my own and not those of my employer. For accuracy and official reference refer to MSDN/ TechNet/ BOL /Other sites that are authorities in their field. Me or employer do not endorse any tools, applications, books, or concepts mentioned on the site. I have documented my personal experience on this site. The information on this site may not be up to date or accurate at times, if you are not sure or have a question, please contact me to verify information.