指定した月の日数を求める - 指定月の末日を求める - C#

C#で指定した月の日数を求めるコードを紹介します。

概要

指定した月の日数を求めるには、DateTime オブジェクトの DaysInMonth メソッドを利用します。
また、別の方法として翌月の1日から1日引く方法もあります。

プログラム例

Windowsフォームアプリケーションを作成します。

UI

下図のUIを作成します。

コード

下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MonthProc
{
  public partial class FormDaysInMonth : Form
  {
    public FormDaysInMonth()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      DateTime input = System.DateTime.ParseExact(textBox1.Text, "yyyy/M",
        System.Globalization.DateTimeFormatInfo.InvariantInfo,
        System.Globalization.DateTimeStyles.NoCurrentDateDefault);

      int Days = DateTime.DaysInMonth(input.Year, input.Month);
      label1.Text = string.Format("{0:d}/{1:d} の日数は{2:d}日です。末日は{0:d}/{1:d}/{2:d}です。",
        input.Year, input.Month, Days);
    }
  }
}

解説

テキストボックスに入力された "yyyy/M" 形式の文字列をDateTime型に変換するコードが下記コードになります。変換はDateTimeオブジェクトのPaseExact()メソッドを利用しています。文字列をDateTime型に変換する詳細についてはこちらの記事を参照してください。
  DateTime input = System.DateTime.ParseExact(textBox1.Text, "yyyy/M",
    System.Globalization.DateTimeFormatInfo.InvariantInfo,
    System.Globalization.DateTimeStyles.NoCurrentDateDefault);

DateTime.DaysInMonth()メソッドを呼び出して指定した月の日数を取得します。取得した日数をラベルに表示します。
  int Days = DateTime.DaysInMonth(input.Year, input.Month);
  label1.Text = string.Format("{0:d}/{1:d} の日数は{2:d}日です。末日は{0:d}/{1:d}/{2:d}です。",
    input.Year, input.Month, Days);

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


テキストボックスに日数または末日を求めたい月を"yyyy/M"形式で入力します。入力ができたら[button1]をクリックします。


ラベルに指定した月の日数と末日が表示されます。


入力を変更して動作確認します。指定した月の日数と末日が表示されることが確認できます。




指定した月の日数と月の末日を求めることができました。
このページのキーワード
  • 指定した月の日数を取得する - 指定月の末日を取得する
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2018-07-27
iPentec all rights reserverd.