Formatting .NET DateTime to display Day suffix (st, nd ,rd , th)

I find it intersting that the MS did not have this by default as part of the Standard DateTime Format Strings for .NET.

So I did my own thing..

public static string FormatDateTime(DateTime date)
    {
        return String.Format("{0:dddd}, {1} {0:MMMM} {0:yyyy}", date, AppendDaySuffix(date.Day) );
    }
public static string AppendDaySuffix(int day)
    {
        string daySuffix = "";
        if (day == 1 || day == 21 || day == 31)
            daySuffix = "st";
        else if (day == 2 || day == 22)
            daySuffix = "nd";
        else if (day == 3 || day == 23)
            daySuffix = "rd";
        else
            daySuffix = "th";
        return (day + daySuffix);
    }


You can download a good pdf  reference for .NET DateTime formats from
http://john-sheehan.com/blog/wp-content/uploads/msnet-formatting-strings.pdf



Advertisement

4 Responses

  1. Thanks for the link…this code would make a great extension method. Nice work.

  2. No Problem, Nice work on the cheat sheet..;)

  3. good work, thats saved me a lot of time! cheers

  4. Thanks a lot! It is odd that Microsoft didn’t include this.

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.