Display ‘st’, ‘nd’, ‘rd’ And ‘th’ Suffix After Day Numbers With Dates In C#

In my recent project, I got the requirement to display dates with suffixes like 21st May 2021, 14th May 2021, etc.

By default, C# doesn’t have any inbuilt feature to display the ‘st‘, ‘nd‘, ‘rd‘, and ‘th‘ suffix after day numbers.

So in this article, we will learn how to display ‘st‘, ‘nd‘, ‘rd‘, and ‘th‘ suffix after day numbers with dates in C#.

GetDayNumberSuffix() method will return ‘st‘, ‘nd‘, ‘rd‘, and ‘th‘ suffix based on the day of given date. FormatDayNumberSuffix() method will append the suffix string to inputted date.

using System;

namespace Day_Suffix
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(FormatDayNumberSuffix(new DateTime(2021, 05, 21)));
            Console.WriteLine(FormatDayNumberSuffix(new DateTime(2021, 05, 22)));
            Console.WriteLine(FormatDayNumberSuffix(new DateTime(2021, 05, 23)));
            Console.WriteLine(FormatDayNumberSuffix(new DateTime(2021, 05, 24)));
        }

        public static string FormatDayNumberSuffix(DateTime inputDateTime)
        {
            return string.Format(inputDateTime.ToString("dd{0} MMMM yyyy"), GetDayNumberSuffix(inputDateTime.Day.ToString()));
        }

        private static string GetDayNumberSuffix(string day)
        {
            string suffix = "th";
            if (int.Parse(day) < 11 || int.Parse(day) > 20)
            {
                day = day.ToCharArray()[^1].ToString();
                switch (day)
                {
                    case "1":
                        suffix = "st";
                        break;
                    case "2":
                        suffix = "nd";
                        break;
                    case "3":
                        suffix = "rd";
                        break;
                }
            }
            return suffix;
        }
    }
}

Output:

Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Also, check CRUD Operations Using .NET 5.0 Web API

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories