给定年份Y和月份M ,任务是使用C#获取一个月中的总天数。
例子:
Input: Y = 2020 N = 02
Output: 29
Input: Y = 1996 N = 06
Output: 30
方法1:使用DateTime.DaysInMonth (年,月)方法:此方法用于获取指定月和年中的天数。
Step 1: Get the year and month.
Step 2: The DateTime.DaysInMonth() is used to get the number of days in a month
Step 3: This integer value is the number of days in the month.
下面是上述方法的实现:
C#
int days = DateTime.DaysInMonth(year, month);;
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));
}
}
输出:
// 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");
}
}
方法2:使用CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(year,month)方法:此方法用于获取指定月份和年份中的天数。 Ÿ欧需要使用System.Globalization命名空间。
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
Step 3: This integer value is the number of days in the month.
下面是上述方法的实现:
C#
Total days in (2020/2) : 29
输出:
int days = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(year, month);;