Given a datetime object, returns the formatted day, "15th" - CSharp System

CSharp examples for System:DateTime Day

Description

Given a datetime object, returns the formatted day, "15th"

Demo Code

//   The contents of this file are subject to the New BSD
using System;/*  w ww  . jav  a 2s . c o  m*/

public class Main{
        /// <summary>
    /// Given a datetime object, returns the formatted day, "15th"
    /// </summary>
    /// <param name="date">The date to extract the string from</param>
    /// <returns></returns>
    public static string GetDateDayWithSuffix(this DateTime date) {
        int dayNumber = date.Day;
        string suffix = "th";

        if (dayNumber == 1 || dayNumber == 21 || dayNumber == 31)
            suffix = "st";
        else if (dayNumber == 2 || dayNumber == 22)
            suffix = "nd";
        else if (dayNumber == 3 || dayNumber == 23)
            suffix = "rd";

        return String.Concat(dayNumber, suffix);
    }
}

Related Tutorials