Open In App

DateTime.DaysInMonth() Method in C#

Improve
Improve
Like Article
Like
Save
Share
Report

This method returns the number of days in the specified month and year. This method always interprets month and year as the month and year of the Gregorian calendar even if the Gregorian calendar is not the current culture’s current calendar.

Syntax:

public static int DaysInMonth (int year, int month);

Return Value: This method return the number of days in the month for the specified year. For example, if month equals 2 for February, the return value will be 28 or 29 depending upon whether the year is a leap year.

Exception: This method will give ArgumentOutOfRangeException if month is less than 1 or greater than 12 or year is less than 1 or greater than 9999.

Below programs illustrate the use of the above-discussed method:

Example 1:




// C# code to demonstrate the
// DaysInMonth(Int32, Int32) Method
using System;
  
class GFG {
  
    // Main Method
    static void Main()
    {
  
        // taking month values
        int Dec = 12;
        int Feb = 2;
  
        // using the method
        int daysindec = DateTime.DaysInMonth(2008, Dec);
  
        Console.WriteLine(daysindec);
  
        // daysinfeb1 gets 29 because the
        // year 2016 was a leap year.
        int daysinfeb1 = DateTime.DaysInMonth(2016, Feb);
  
        Console.WriteLine(daysinfeb1);
  
        // daysinfeb2 gets 28 because
        // the year 2018 was not a leap year.
        int daysinfeb2 = DateTime.DaysInMonth(2018, Feb);
  
        Console.WriteLine(daysinfeb2);
    }
}


Output:

31
29
28

Example 2:




// C# code to demonstrate the
// DaysInMonth(Int32, Int32) Method
using System;
  
class GFG {
  
    // Main Method
    static void Main()
    {
  
        // taking month and year's value
        int y = 10000;
        int m = 7;
  
        // using the method will give error
        // as the value of the year is greater
        // than 10000
        int res = DateTime.DaysInMonth(y, m);
  
        Console.WriteLine(res);
    }
}


Runtime Error:

Unhandled Exception:
System.ArgumentOutOfRangeException: Year must be between 1 and 9999.
Parameter name: year

Reference:



Last Updated : 22 Jan, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads