如何在c#中生成类似“11月1日”的日期格式

我怎样才能在c#中提到日期格式。

  • 对于2010年11月1日,它应显示为:11月1日

  • 对于2010年11月30日,它应显示为:11月30日

我们可以使用任何日期格式或制作一个自定义函数,返回1 – >’st’,2->’nd’3 – >’rd’,任何日期no – >’th’。

以下代码基于从整数生成序数的答案 :

public static string ToOrdinal(int number) { switch(number % 100) { case 11: case 12: case 13: return number.ToString() + "th"; } switch(number % 10) { case 1: return number.ToString() + "st"; case 2: return number.ToString() + "nd"; case 3: return number.ToString() + "rd"; default: return number.ToString() + "th"; } } 

比你可以生成输出字符串:

 public static string GenerateDateString(DateTime value) { return string.Format( "{0} {1:MMMM}", ToOrdinal(value.Day), value); } 

所以这是一个带有扩展方法的完整解决方案。 适用于C#3.0及以上版本。 主要是抄袭Nikhil的作品:

 public static class DateTimeExtensions { static string[] extensions = // 0 1 2 3 4 5 6 7 8 9 { "th", "st", "nd", "rd", "th", "th", "th", "tn", "th", "th", // 10 11 12 13 14 15 16 17 18 19 "th", "th", "th", "th", "th", "th", "th", "tn", "th", "th", // 20 21 22 23 24 25 26 27 28 29 "th", "st", "nd", "rd", "th", "th", "th", "tn", "th", "th", // 30 31 "th", "st" }; public static string ToSpecialString(this DateTime dt) { string s = dt.ToString(" MMMM yyyy"); string t = string.Format("{0}{1}", dt.Day, extensions[dt.Day]); return t + s; } } 

测试/使用像这样:

 Console.WriteLine(DateTime.Now.ToSpecialString()); Console.WriteLine(new DateTime(1990, 11, 12).ToSpecialString()); Console.WriteLine(new DateTime(1990, 1, 1).ToSpecialString()); Console.WriteLine(new DateTime(1990, 1, 2).ToSpecialString()); Console.WriteLine(new DateTime(1990, 1, 3).ToSpecialString()); Console.WriteLine(new DateTime(1990, 1, 4).ToSpecialString()); Console.WriteLine(new DateTime(1990, 12, 15).ToSpecialString()); Console.WriteLine(new DateTime(1990, 8, 19).ToSpecialString()); Console.WriteLine(new DateTime(1990, 9, 22).ToSpecialString()); Console.ReadKey(); 

希望有帮助。

这样的事情应该有效……

 using System; using System.Text; namespace Program { class Demo { static string[] extensions = // 0 1 2 3 4 5 6 7 8 9 { "th", "st", "nd", "rd", "th", "th", "th", "tn", "th", "th", // 10 11 12 13 14 15 16 17 18 19 "th", "th", "th", "th", "th", "th", "th", "tn", "th", "th", // 20 21 22 23 24 25 26 27 28 29 "th", "st", "nd", "rd", "th", "th", "th", "tn", "th", "th", // 30 31 "th", "st" }; public static void Main() { String strTestDate = "02-11-2007"; DateTime coverdate = DateTime.ParseExact(strTestDate, "dd-MM-yyyy", null); string s = coverdate.ToString(" MMMM yyyy"); string t = string.Format("{0}{1}",coverdate.Day,extensions[coverdate.Day]); string result = t + s; } } } 

我很确定没有数据时间例程可以将日期显示为1日或30日。

我最近从头开始写了一些代码。 我想你也需要这样做。

我没有方便的代码,但我只创建了一个字符串数组,其中包含每个数字的字母(“th”,“st”,“nd”,“rd”,“th”等)。 然后mod对10并使用余数作为数组的索引。 您只需将该字符串附加到您的号码即可。

您可以使用正则表达式提取日期和月份。 然后,将所有月份的名称存储在一个数组中,并使用.startsWith获取该月份的正确名称。 您可以使用一个简单的case来查看您是否需要’st’,’nd’,’rd’或’th’。

我跟着来自JSL vscontrol的字符串示例博客,它最后有一个错误,他忘了连接行开头的日期编号所以它应该是

  return strNum + ordinal + str; 

并不是 !

  return ordinal + str;