此方法返回指定月份和年份中的天數。即使公曆不是當前文化的當前日曆,此方法也始終將月份和年份解釋為公曆的月份和年份。
用法:
public static int DaysInMonth (int year, int month);
返回值:此方法返回指定年份的月份中的天數。例如,如果2月的月份等於2,則返回值將為28或29,具體取決於年份是否為leap年。
異常:如果月份小於1或大於12或年份小於1或大於9999,則此方法將提供ArgumentOutOfRangeException。
以下示例程序旨在說明上述方法的用法:
示例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);
}
}
輸出:
31 29 28
示例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);
}
}
運行時錯誤:
Unhandled Exception:
System.ArgumentOutOfRangeException: Year must be between 1 and 9999.
Parameter name: year
參考:
相關用法
- C# Queue.Contains()用法及代碼示例
- C# Random.Next()用法及代碼示例
- C# Uri.ToString()用法及代碼示例
- C# Uri.FromHex()用法及代碼示例
- C# DateTime.Add()用法及代碼示例
- C# Uri.IsWellFormedOriginalString()用法及代碼示例
- C# TimeSpan.Add()用法及代碼示例
- C# Uri.GetHashCode()用法及代碼示例
- C# Uri.IsHexDigit()用法及代碼示例
注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 DateTime.DaysInMonth() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。