How can i format 07/03/2012 to March 7th,2012 in c

2019-01-11 03:35发布

问题:

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

回答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



回答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)


回答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


回答4:

No, there is nothing in string.Format() that will give you ordinals (1st, 2nd, 3rd, 4th and so on).

You can combine the date format like suggested in other answers, with your own ordinal as suggested for example in this answer

Is there an easy way to create ordinals in C#?

string Format(DateTime date)
{
    int dayNo = date.Day;
    return string.Format("{0} {1}{2}, {3}", 
                date.ToString("MMMM"), dayNo, AddOrdinal(dayNo), date.Year); 
}


回答5:

public static class IntegerExtensions
{
    /// <summary>
    /// converts an integer to its ordinal representation
    /// </summary>
    public static String AsOrdinal(this Int32 number)
    {
        if (number < 0)
            throw new ArgumentOutOfRangeException("number");

        var work = number.ToString("n0");

        var modOf100 = number % 100;

        if (modOf100 == 11 || modOf100 == 12 || modOf100 == 13)
            return work + "th";

        switch (number % 10)
        {
            case 1:
                work += "st"; break;
            case 2:
                work += "nd"; break;
            case 3:
                work += "rd"; break;
           default:
                work += "th"; break;
        }

        return work;
    }
}

Proof:

[TestFixture]
class IntegerExtensionTests
{
    [Test]
    public void TestCases_1s_10s_100s_1000s()
    {
        Assert.AreEqual("1st", 1.AsOrdinal());
        Assert.AreEqual("2nd", 2.AsOrdinal());
        Assert.AreEqual("3rd", 3.AsOrdinal());

        foreach (var integer in Enumerable.Range(4, 6))
            Assert.AreEqual(String.Format("{0:n0}th", integer), integer.AsOrdinal());

        Assert.AreEqual("11th", 11.AsOrdinal());
        Assert.AreEqual("12th", 12.AsOrdinal());
        Assert.AreEqual("13th", 13.AsOrdinal());

        foreach (var integer in Enumerable.Range(14, 6))
            Assert.AreEqual(String.Format("{0:n0}th", integer), integer.AsOrdinal());

        Assert.AreEqual("21st", 21.AsOrdinal());
        Assert.AreEqual("22nd", 22.AsOrdinal());
        Assert.AreEqual("23rd", 23.AsOrdinal());

        foreach (var integer in Enumerable.Range(24, 6))
            Assert.AreEqual(String.Format("{0:n0}th", integer), integer.AsOrdinal());

        Assert.AreEqual("31st", 31.AsOrdinal());
        Assert.AreEqual("32nd", 32.AsOrdinal());
        Assert.AreEqual("33rd", 33.AsOrdinal());

        //then just jump to 100

        Assert.AreEqual("101st", 101.AsOrdinal());
        Assert.AreEqual("102nd", 102.AsOrdinal());
        Assert.AreEqual("103rd", 103.AsOrdinal());

        foreach (var integer in Enumerable.Range(104, 6))
            Assert.AreEqual(String.Format("{0:n0}th", integer), integer.AsOrdinal());

        Assert.AreEqual("111th", 111.AsOrdinal());
        Assert.AreEqual("112th", 112.AsOrdinal());
        Assert.AreEqual("113th", 113.AsOrdinal());

        foreach (var integer in Enumerable.Range(114, 6))
            Assert.AreEqual(String.Format("{0:n0}th", integer), integer.AsOrdinal());

        Assert.AreEqual("121st", 121.AsOrdinal());
        Assert.AreEqual("122nd", 122.AsOrdinal());
        Assert.AreEqual("123rd", 123.AsOrdinal());

        foreach (var integer in Enumerable.Range(124, 6))
            Assert.AreEqual(String.Format("{0:n0}th", integer), integer.AsOrdinal());

        //then just jump to 1000

        Assert.AreEqual("1,001st", 1001.AsOrdinal());
        Assert.AreEqual("1,002nd", 1002.AsOrdinal());
        Assert.AreEqual("1,003rd", 1003.AsOrdinal());

        foreach (var integer in Enumerable.Range(1004, 6))
            Assert.AreEqual(String.Format("{0:n0}th", integer), integer.AsOrdinal());

        Assert.AreEqual("1,011th", 1011.AsOrdinal());
        Assert.AreEqual("1,012th", 1012.AsOrdinal());
        Assert.AreEqual("1,013th", 1013.AsOrdinal());

        foreach (var integer in Enumerable.Range(1014, 6))
            Assert.AreEqual(String.Format("{0:n0}th", integer), integer.AsOrdinal());

        Assert.AreEqual("1,021st", 1021.AsOrdinal());
        Assert.AreEqual("1,022nd", 1022.AsOrdinal());
        Assert.AreEqual("1,023rd", 1023.AsOrdinal());

        foreach (var integer in Enumerable.Range(1024, 6))
            Assert.AreEqual(String.Format("{0:n0}th", integer), integer.AsOrdinal());
    }
}


回答6:

Based on Rob Levine's answer and the comments on that answer... I've adapted as an extension method on DateTime so you can just call:

var formattedDate = date.Friendly();

Here's the extension method:

public static class DateFormatter
{
  public static string Friendly(this DateTime dt)
  {
    string suffix;

    switch (dt.Day)
    {
      case 1:
      case 21:
      case 31:
        suffix = "st";
        break;
      case 2:
      case 22:
        suffix = "nd";
        break;
      case 3:
      case 23:
        suffix = "rd";
        break;
      default:
        suffix = "th";
        break;
    }

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


回答7:

Here is another version of the Ordinalize() extension, short and sweet:

public static string Ordinalize(this int x)
{
    return x.ToString() + 
        ((x % 10 == 1 && x != 11) 
        ? "st"
        : (x % 10 == 2 && x != 12) 
        ? "nd"
        : (x % 10 == 3 && x != 13) 
        ? "rd"
        : "th");
}

and then call that extension like this

myDate.Day.Ordinalize()

or

myAnyNumber.Ordinalize() 


回答8:

DateTime dt = new DateTime(args);
String.Format("{0:ddd, MMM d, yyyy}", dt); 

// "Sun, Mar 9, 2008"



回答9:

Use following Code:

DateTime thisDate1 = new DateTime(2011, 6, 10);
Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".");

DateTimeOffset thisDate2 = new DateTimeOffset(2011, 6, 10, 15, 24, 16, 
                                              TimeSpan.Zero);
Console.WriteLine("The current date and time: {0:MM/dd/yy H:mm:ss zzz}", 
                   thisDate2); 
// The example displays the following output:
//    Today is June 10, 2011.
//    The current date and time: 06/10/11 15:24:16 +00:00