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#
using System;
public class GFG{
static int getdays( int year, int month)
{
int days = DateTime.DaysInMonth(year, month);
return days;
}
static public void Main ()
{
int Y = 2020;
int M = 02;
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#
using System;
using System.Globalization;
public class GFG{
static int getdays( int year, int month)
{
int days = CultureInfo.CurrentCulture.
Calendar.GetDaysInMonth(year, month);
return days;
}
static public void Main ()
{
int Y = 2020;
int M = 02;
Console.WriteLine( "Total days in ("
+ Y + "/" + M + ") : " + getdays(Y, M)
+ " days" );
}
}
|
Output:
Total days in (2020/2) : 29 days
Share your thoughts in the comments
Please Login to comment...