C# Datetime Month

C# Datetime Month



  This post explains various formats of getting Month part of the date.

Month is a read only property of DateTime object. It returns integer corresponding to month order.

e.g.   


   For January it returns 1, February it returns 2 and so on.

Code:

protected void Button1_Click(object sender, EventArgs e)
  {

      DateTime dt = DateTime.Now;

      Response.Write( dt.Month ); 

      Response.Write( dt.ToString("M")  );     

      Response.Write(dt.ToString("MM")); 

      Response.Write(dt.ToString("MMM")); 
 }


Output:

8
August 25
08
Aug
Aug

Description: First we have created dt as a new instance of DateTime. Later we converted DateTime instance into various month formats. 

Code Description
dt.Month       Returns integer value corresponding to month.
In above example it returned 8th which is august month of the  
year.
dt.ToString("M")  Date instance is converted in to string representation with specified format.
dt.ToString("MM") Date and Month in integer format
dt.ToString("MMM") 3 character string of month    


First Month of Year:

Code:


protected void Button1_Click(object sender, EventArgs e)
  {

      DateTime dt = DateTime.Now;
      int currentMonth = dt.Month;
      dt = dt.AddMonths(-(currentMonth - 1));
      Response.Write(dt.ToString("MMMM"));      

  }


Output:

January

Array of Month string:

Code


protected void Button1_Click(object sender, EventArgs e)
    {

        DateTime dt = DateTime.Now;

        int currentMonth = dt.Month;

        dt = dt.AddMonths(-(currentMonth - 1));

        string[] arrMonth = new string[12];

       for(int i=0; i<=11 ; i++)
       {

            arrMonth[i] = dt.ToString("MMMM");
            dt = dt.AddMonths(1);
            Response.Write( arrMonth[i] );
        }       

    }     






 

Currently rated 4.0 by 2 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5