指定した年と月に含まれる日数を取得するには、DateTime の DaysInMonth メソッドを使用します。
引数に取得したい年と月を指定することで、指定した年と月に含まれる日数が返されます。
C#
// 2004年02月の日数を取得する
int iDaysInMonth = DateTime.DaysInMonth(2004, 2);
// 取得した日数を表示する
MessageBox.Show(iDaysInMonth.ToString());VB.NET
' 2004年02月の日数を取得する
Dim iDaysInMonth As Integer = DateTime.DaysInMonth(2004, 2)
' 取得した日数を表示する
MessageBox.Show(iDaysInMonth.ToString())J# [Java]
// 2004年02月の日数を取得する
int iDaysInMonth = System.DateTime.DaysInMonth(2004, 2);
// 取得した日数を表示する
MessageBox.Show(System.Convert.ToString(iDaysInMonth));VB [VB6]
VB6 では、該当する関数はありませんので、指定した年と月に含まれる日数を返す関数を自作します。
閏年 (うるう年) を考慮するために、自作の IsLeapYear 関数を使用しています。
この自作の IsLeapYear 関数については、閏年 (うるう年) かどうか判断する をご覧ください。
' -------------------------------------------------------------------------------
' 指定した年と月に含まれる日数を取得します。
'
' @Param iYear 対象となる年。
' @Param iMonth 対象となる月。
' @Return 指定した年と月に含まれる日数。
' -------------------------------------------------------------------------------
Public Function DaysInMonth(ByVal iYear As Integer, ByVal iMonth As Integer) As Integer
Select Case iMonth
Case 2
If IsLeapYear(iYear) Then
DaysInMonth = 29
Else
DaysInMonth = 28
End If
Case 4, 6, 9, 11
DaysInMonth = 30
Case 1, 3, 5, 7, 8, 10, 12
DaysInMonth = 31
End Select
End Function使用例は以下のようになります。
' 指定した年と月に含まれる日数を格納するための変数を宣言する
Dim iDaysInMonth As Integer
' 2004年02月の日数を取得する
iDaysInMonth = DaysInMonth(2004, 2)
' 取得した日数を表示する
Call MsgBox(CStr(iDaysInMonth))