指定した月の日数(月末日)の取得
C#でカレンダー機能や日付ベースの集計処理を実装する際、「指定した年・月が、何日まで存在するのか」(28日、29日、30日、31日のどれか)という情報が必要になることがあります。
特に2月は、うるう年(閏年)かどうかによって日数が変わるため、判定ロジックは複雑になりがちです。
C#のDateTime構造体は、この計算を簡単に行うためのDaysInMonthという静的メソッドを提供しています。
DateTime.DaysInMonth(int year, int month) メソッド
DateTime.DaysInMonthは、引数として渡されたyear(年)とmonth(月)に基づいて、その月が持つ日数をint型で返します。
year: 年を指定します(例:2025)。month: 月を指定します(1~12)。
このメソッドは、対象の年がうるう年であるかどうかを自動的に判定し、2月の日数(28または29)を正しく返します。
コード例1:基本的な使い方
DaysInMonthメソッドを使用し、2025年10月(31日まで)の日数を取得する例です。
using System;
public class DaysInMonthBasicExample
{
public static void Main()
{
int targetYear = 2025;
int targetMonth = 10; // 10月
// 2025年10月の日数を取得
int days = DateTime.DaysInMonth(targetYear, targetMonth);
Console.WriteLine($"{targetYear}年 {targetMonth}月は、{days} 日まであります。");
}
}
出力結果:
2025年 10月は、31 日まであります。
コード例2:うるう年(閏年)の自動判定
DaysInMonthメソッドの最大の利点は、うるう年の計算を自動で行う点です。
うるう年(2024年)と平年(2025年)の2月の日数をそれぞれ取得し、結果を比較します。
using System;
public class LeapYearDaysInMonthExample
{
public static void Main()
{
int targetMonth = 2; // 2月
// --- 1. うるう年 (2024年) の2月 ---
int leapYear = 2024;
int daysInLeapYear = DateTime.DaysInMonth(leapYear, targetMonth);
Console.WriteLine($"{leapYear}年 (うるう年) の {targetMonth}月は、{daysInLeapYear} 日まであります。");
// --- 2. 平年 (2025年) の2月 ---
int normalYear = 2025;
int daysInNormalYear = DateTime.DaysInMonth(normalYear, targetMonth);
Console.WriteLine($"{normalYear}年 (平年) の {targetMonth}月は、{daysInNormalYear} 日まであります。");
}
}
出力結果:
2024年 (うるう年) の 2月は、29 日まであります。
2025年 (平年) の 2月は、28 日まであります。
まとめ
DateTime.DaysInMonth(int year, int month)メソッドは、C#で指定した月の日数(つまり、その月の最終日)をint型で取得するための、最も簡単で信頼性の高い方法です。
うるう年(2月29日)の判定ロジックを自前で実装する必要はなく、このメソッドを呼び出すだけで、グレゴリオ暦に基づいた正確な日数が返されます。
