Advertisement

Latest Post

Thursday, 4 May 2017

How to Display 'st', 'nd', 'rd' and 'th' suffix to day numbers in Formatted Dates using C#

I have created common method using c# that display 'st', 'nd', 'rd' and 'th' suffix to day numbers in Formatted Dates

here is method


public string Format(string format, object arg, IFormatProvider formatProvider)
   {
            if (arg != null)
            {
                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("{1}{2} {0:MMM}, {0:yyyy}", arg, dt.Day, suffix);
            }
            else
                return String.Empty;
        }

Sql Server function to display 'st', 'nd', 'rd' and 'th' suffix to day numbers

Government Jobs