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

    }     






 

Tags:

DateTimeTryParse using C# and VB.net exampleC# DateTime DifferenceC# get month number from month textC# DateTime ToString()C# Parse method of DateTimeDateTime.Today Vs DateTime.NowC# DateTimeIFormatProvider DateTime C#.netDateTimeTryParse with IFormatProvider culture information using c#C# Convert String To DateTimeDateTime in C# current Date and Time

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.