How can i format 07/03/2012 to March 7th,2012 in c# [duplicate]

Any one please help i need to show the date 03/03/2012 as March 3rd,2012 etc


Solution 1:

You can create your own custom format provider to do this:

public class MyCustomDateProvider: IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;

        return null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (!(arg is DateTime)) throw new NotSupportedException();

        var dt = (DateTime) arg;

        string suffix;

        if (new[] {11, 12, 13}.Contains(dt.Day))
        {
            suffix = "th";
        }
        else if (dt.Day % 10 == 1)
        {
            suffix = "st";
        }
        else if (dt.Day % 10 == 2)
        {
            suffix = "nd";
        }
        else if (dt.Day % 10 == 3)
        {
            suffix = "rd";
        }
        else
        {
            suffix = "th";
        }

        return string.Format("{0:MMMM} {1}{2}, {0:yyyy}", arg, dt.Day, suffix);
    }
}

This can then be called like this:

var formattedDate = string.Format(new MyCustomDateProvider(), "{0}", date);

Resulting in (for example):

March 3rd, 2012

Solution 2:

Humanizer meets all your .NET needs for manipulating and displaying strings, enums, dates, times, timespans, numbers and quantities

To install Humanizer, run the following command in the Package Manager Console

PM> Install-Package Humanizer

Ordinalize turns a number into an ordinal string used to denote the position in an ordered sequence such as 1st, 2nd, 3rd, 4th:

1.Ordinalize() => "1st"
5.Ordinalize() => "5th"

Then you can use:

String.Format("{0} {1:MMMM yyyy}", date.Day.Ordinalize(), date)

Solution 3:

Custom Date and Time Format Strings

date.ToString("MMMM d, yyyy")

Or if you need the "rd" too:

string.Format("{0} {1}, {2}", date.ToString("MMMM"), date.Day.Ordinal(), date.ToString("yyyy"))
  • the Ordinal() method can be found here