先月の月末の値のDateTimeオブジェクトを取得する (先月の月末のDateTimeオブジェクトを作成する) - C#

先月の月末の値のDateTimeオブジェクトを取得するコードを紹介します。

概要

先月の月末の日付を表すDateTimeオブジェクトを取得したい場合があります。 先月の月末のDateTimeオブジェクトを取得するコードを紹介します。

プログラム1: 月の日数を求める方法

当月の日数を求めて、月末の日付を取得してDateTimeオブジェクトを取得する方法です。
Windows Formアプリケーションを作成します。

UI

下図のフォームを作成します。4つボタンが配置されていますが、今回は[先月の月末の日付]のボタンのみ利用します。

コード

下記のコードを記述します。ボタンのClickイベントを実装します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace CalcDateTime2020
{
  public partial class FormCalcMonth : Form
  {
    public FormCalcMonth()
    {
      InitializeComponent();
    }

    private void button4_Click(object sender, EventArgs e)
    {
      DateTime last_month = DateTime.Now.AddMonths(-1);
      int last_month_days = DateTime.DaysInMonth(last_month.Year, last_month.Month);
      DateTime dt = new DateTime(last_month.Year, last_month.Month, last_month_days);
      textBox1.Text = dt.ToString("yyyy/MM/dd");
    }
  }
}

解説

現在の日付から一か月前の日付を取得します。
  DateTime last_month = DateTime.Now.AddMonths(-1);

一か月前の年と月を利用して、一か月前の月の日数を取得します。月の日数の取得の詳細はこちらの記事を参照してください。
  int last_month_days = DateTime.DaysInMonth(last_month.Year, last_month.Month);

一か月前の年、月、月の日数を利用してDateTimeオブジェクトを作成します。この値が前月の月末の値になります。
  DateTime dt = new DateTime(last_month.Year, last_month.Month, last_month_days);

作成したDateTimeオブジェクトの値をテキストボックスに表示します。
  textBox1.Text = dt.ToString("yyyy/MM/dd");

プログラム2: 今月の月初から1日引く方法

UI

下図のフォームを作成します。先のプログラムと同じUIです。4つボタンが配置されていますが、今回は[先月の月末の日付]のボタンのみ利用します。

コード

下記のコードを記述します。ボタンのClickイベントを実装します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace CalcDateTime2020
{
  public partial class FormCalcMonth : Form
  {
    public FormCalcMonth()
    {
      InitializeComponent();
    }

    private void button4_Click(object sender, EventArgs e)
    {
      DateTime this_month_start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
      DateTime dt = this_month_start.AddDays(-1);
      textBox1.Text = dt.ToString("yyyy/MM/dd");
    }
  }
}

解説

今月の月初のDateTimeオブジェクトを取得し、その日付から1日戻ることで、先月の月末の日付の値を取得します。

今月の月初の値を取得します。詳しくはこちらの記事を参照してください。
  DateTime this_month_start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

今月の月初から1日引くことで、先月の月末の日付になります。
  DateTime dt = this_month_start.AddDays(-1);

取得したDateTimeオブジェクトの値をテキストボックスに表示します。
  textBox1.Text = dt.ToString("yyyy/MM/dd");

実行結果

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


先月の月末の日付]のボタンをクリックします。先月の月末の日付がテキストボックスに表示されます。


先月の月末の日付を表すDateTimeオブジェクトが取得できました。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2020-08-10
作成日: 2020-08-07
iPentec all rights reserverd.