C# - 月の最終日を取得する

月末日を取得するには、DateTime 構造体の DaysInMonthメソッド を使用します。

最終日を取得する方法

DateTime.DaysInMonthメソッド の引数に 年と月 を渡すと、その月が何日あるかを数値で返します。
// DateTime.DaysInMonth の使用方法
int 日数(1-31) = DateTime.DaysInMonth(年, 月);

サンプルコード

2024年2月の最終日を取得し、表示します。
// 2024年2月の日数を取得する
int daysInMonth = DateTime.DaysInMonth(2024, 2);

// 結果="2024年2月の最終日は29日"
Console.WriteLine($"2024年2月の最終日は{daysInMonth}日");
サンプルコードの実行結果(Visual Studio)
サンプルコードの実行結果(Visual Studio)

最終日が設定されたDateTime型を取得する

DateTime のコンストラクタに DateTime.DaysInMonth で取得した日付を渡します。
DateTime 現在年月日 = DateTime.Today;
DateTime 月末 = new DateTime(現在年月日.Year, 現在年月日.Month, DateTime.DaysInMonth(現在年月日.Year, 現在年月日.Month));

検証環境