.Net Framework C#

C# - DateTime.DaysInMonth 特定日からその月の全日を取得する

2013年9月12日

特定日からその月の全日を取得する方法を調べたところ、DateTime に DaysInMonth というメソッドが用意されていました。DaysInMonth メソッド自体は月の持つ日数を返すだけですので、日数分ループして日付を用意しています。

protected void Page_Load(object sender, EventArgs e)
{
    // 日を保存するリスト
    List<DateTime> days = new List<DateTime>();

    // 来月の日付を取得
    DateTime nextMonth = DateTime.Today.AddMonths(1);

    // DateTime.DaysInMonth を使って選択日の月の日数を取得
    int daysInNextMonth = DateTime.DaysInMonth(nextMonth.Year, nextMonth.Month);

    // 日数分カレンダーに追加
    for (int i = 0; i < daysInNextMonth; i++)
    {
        DateTime date = new DateTime(nextMonth.Year, nextMonth.Month, i + 1);

        days.Add(date);
    }
}

参考:DateTime.DaysInMonth メソッド

-.Net Framework, C#