Skip to content
Related Articles

Related Articles

How to Get a Total Number of Days in a Month using built in Functions in C#?
  • Last Updated : 28 May, 2020

Given a year Y and month M, the task is to get a total number of days in a month in C#.

Examples:

Input: Y = 2020 N = 02
Output: 29
  
Input: Y = 1996 N = 06
Output: 30

Method 1: Using DateTime.DaysInMonth(year, month) Method: This method is used to get the number of days in the specified month and year.

Step 1: Get the year and month.

Step 2: The DateTime.DaysInMonth() is used to get the number of days in a month



int days = DateTime.DaysInMonth(year, month);;

Step 3: This integer value is the number of days in the month.

Below is the implementation of the above approach:

C#




// C# program to Get a Total Number
// of Days in a Month
using System; 
    
public class GFG{ 
      
    // function to get the full month name 
    static int getdays(int year, int month)  
    
        int days = DateTime.DaysInMonth(year, month);
          
        return days;
    
      
    static public void Main () 
    {  
        int Y = 2020; // year
        int M = 02; // month
          
        Console.WriteLine("Total days in ("
        + Y + "/" + M + ") : "+ getdays(Y, M)); 
    }  
}

Output:

Total days in (2020/2) : 29

Method 2: Using CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(year,month) Method: This method is used to get the number of days in the specified month and year. You need to use  System.Globalization namespace.

Step 1: Get the year and month.

Step 2: The CultureInfo.CurrentCulture.Calendar.GetDaysInMonth() is used to get the number of days in a month

int days = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(year, month);;

Step 3: This integer value is the number of days in the month.

Below is the implementation of the above approach:

C#




// C# program to Get a Total Number
// of Days in a Month
using System; 
using System.Globalization;
    
public class GFG{ 
      
    // function to get the full month name 
    static int getdays(int year, int month)  
    
        int days = CultureInfo.CurrentCulture.
        Calendar.GetDaysInMonth(year, month);
          
        return days;
    
      
    static public void Main () 
    {  
        int Y = 2020; // year
        int M = 02; // month
          
        Console.WriteLine("Total days in ("
        + Y + "/" + M + ") : "+ getdays(Y, M)
        + " days"); 
    }  
}

Output:

Total days in (2020/2) : 29 days
My Personal Notes arrow_drop_up
Recommended Articles
Page :