C# get the number of days in a month

Ok this isn't the longest blog post, but it contains a handy little code snippet. Sometimes you find yourself needing to know the number of days in any given month. The code below will get you the last day of the month. I'm using the current month but you could use any month. You just need to know the month and year you're looking for. The magic lies in the DateTime.DaysInMonth method. You pass in the year and month and it returns the number of days in that month. The code below is pretty self explanatory.

static void Main( string[] args )
{
   DateTime now = DateTime.Now;

   int daysInMonth = DateTime.DaysInMonth( now.Year, now.Month );

   String dateFormat = String.Format( "Last day of the month is - {0}/{1}/{2}", now.Month, daysInMonth, now.Year);

   Console.WriteLine( dateFormat);

   Console.ReadKey();

}

And a brief picture showing the output, obviously I ran this is October 2011.

Comments

Popular posts from this blog

String.Replace vs Regex.Replace

C# Form Application in Kiosk Mode/Fullscreen

Javascript numeric only text box