我如何格式化07/03/2012到2012年3月7日在c#

时间:2012-03-07 12:33:41

标签: c# datetime formatting

任何人请帮忙 我需要将日期03/03/2012显示为2012年3月3日等

9 个答案:

答案 0 :(得分:47)

您可以创建自己的自定义格式提供程序来执行此操作:

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);
    }
}

然后可以这样调用:

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

导致(例如):

  

2012年3月3日

答案 1 :(得分:28)

Humanizer满足您操作和显示字符串,枚举,日期,时间,时间跨度,数字和数量的所有.NET需求

要安装Humanizer,请在程序包管理器控制台中运行以下命令

PM> Install-Package Humanizer

Ordinalize将一个数字转换为一个序数字符串,用于表示有序序列中的位置,如第1,第2,第3,第4:

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

然后你可以使用:

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

答案 2 :(得分:10)

Custom Date and Time Format Strings

date.ToString("MMMM d, yyyy")

或者如果您还需要“rd”:

string.Format("{0} {1}, {2}", date.ToString("MMMM"), date.Day.Ordinal(), date.ToString("yyyy"))
  • 可以找到Ordinal() <{1}}方法here

答案 3 :(得分:3)

不,string.Format()中没有任何内容可以为您提供序数(第1,第2,第3,第4等)。

您可以将其他答案中建议的日期格式与您自己的序数结合起来,例如在此答案中建议

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); 
}

答案 4 :(得分:3)

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;
    }
}

证明:

[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());
    }
}

答案 5 :(得分:2)

基于Rob Levine的回答以及对该答案的评论......我已经在DateTime上作为扩展方法进行了调整,因此您可以致电:

var formattedDate = date.Friendly();

这是扩展方法:

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);
  }
}

答案 6 :(得分:0)

这是Ordinalize()扩展的另一个版本,short和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");
}

然后像这样调用该扩展

myDate.Day.Ordinalize()

myAnyNumber.Ordinalize() 

答案 7 :(得分:-3)

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

//“Sun,2008年3月9日”

答案 8 :(得分:-4)

使用以下代码:

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