C# DateTime DaysInMonth

Description

DateTime DaysInMonth returns the number of days in the specified month and year.

Syntax

DateTime.DaysInMonth has the following syntax.


public static int DaysInMonth(
  int year,
  int month
)

Parameters

DateTime.DaysInMonth has the following parameters.

  • year - The year.
  • month - The month (a number ranging from 1 to 12).

Returns

DateTime.DaysInMonth method returns The number of days in month for the specified year. For example, if month equals 2 for February, the return value is 28 or 29 depending upon whether year is a leap year.

Example

The following example demonstrates how to use the DaysInMonth method to determine the number of days in July 2001, February 1998 (a non-leap year), and February 1996 (a leap year).


//from   w w  w . jav a  2 s.c  o  m
using System;

class Example
{
  static void Main()
  {
    const int July = 7;
    const int Feb = 2;

    int daysInJuly = System.DateTime.DaysInMonth(2001, July);
        Console.WriteLine(daysInJuly);

    // daysInFeb gets 28 because the year 1998 was not a leap year. 
    int daysInFeb = System.DateTime.DaysInMonth(1998, Feb);
        Console.WriteLine(daysInFeb);

    // daysInFebLeap gets 29 because the year 1996 was a leap year. 
    int daysInFebLeap = System.DateTime.DaysInMonth(1996, Feb);
    Console.WriteLine(daysInFebLeap);
  }
}

The code above generates the following result.

Example 2

The following example displays the number of days in each month of a year specified in an integer array.


using System;//w  w  w  .j a  va2s .c om
using System.Globalization;

public class Example
{
   public static void Main()
   {
      int[] years = { 2012, 2014 };
      DateTimeFormatInfo dtfi = DateTimeFormatInfo.CurrentInfo;
      Console.WriteLine("Days in the Month for the {0} culture " +
                        "using the {1} calendar\n", 
                        CultureInfo.CurrentCulture.Name, 
                        dtfi.Calendar.GetType().Name.Replace("Calendar", ""));
      Console.WriteLine("{0,-10}{1,-15}{2,4}\n", "Year", "Month", "Days");

      foreach (var year in years) {
         for (int ctr = 0; ctr <= dtfi.MonthNames.Length - 1; ctr++) {
            if (String.IsNullOrEmpty(dtfi.MonthNames[ctr]))  
               continue;

            Console.WriteLine("{0,-10}{1,-15}{2,4}", year, 
                              dtfi.MonthNames[ctr], 
                              DateTime.DaysInMonth(year, ctr + 1));
         }
         Console.WriteLine(); 
      }
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version