How Do I Produce a Date format like “1st November” in c#

后端 未结 6 946
醉梦人生
醉梦人生 2020-12-06 05:31

How can i get below mentions date format in c#.

  • For 1-Nov-2010 it should be display as : 1st November

  • For 30-Nov-2010 it should be display a

6条回答
  •  半阙折子戏
    2020-12-06 06:18

    So here is a fullish solution with extension methods. Works for C# 3.0 and above. Mostly plagiarized Nikhil's work:

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

    Test/Use Like this:

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

    Hope that Helps.

提交回复
热议问题