先月の月初の値のDateTimeオブジェクトを取得するコードを紹介します。
概要
先月の月初の日付を表すDateTimeオブジェクトを取得したい場合があります。
先月の月初のDateTimeオブジェクトを取得する場合は、先月の年、月と月初の日付"1"を利用して、DateTimeオブジェクトを生成する方法が簡単です。
プログラム
Windows Formアプリケーションを作成します。
UI
下図のフォームを作成します。テキストボックスとボタンを配置します。
4つボタンが配置されていますが、今回は[先月の月初の日付]のボタンのみ利用します。
コード
下記のコードを記述します。Buttonの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 button2_Click(object sender, EventArgs e)
{
DateTime last_month = DateTime.Now.AddMonths(-1);
DateTime last_month_beginning = new DateTime(last_month.Year, last_month.Month, 1);
textBox1.Text = last_month_beginning.ToString("yyyy/MM/dd");
}
}
}
解説
DateTime.Now
を利用して現在の日時を取得し、
AddMonths(1-)
メソッドを呼び出して現在の日時の一か月前の日時を取得します。
DateTime last_month = DateTime.Now.AddMonths(-1);
new演算子を利用して、DateTimeオブジェクトを作成します。コンストラクタに年、月、日を与えるとその日付のDateTimeオブジェクトを作成するコンストラクタがあるため、こちらを利用します。先月の年、月は先ほど求めた
last_month
の値を利用します。また、日付は月初の日付を指定するため
1
を与えます。
DateTime last_month_beginning = new DateTime(last_month.Year, last_month.Month, 1);
作成したDateTimeオブジェクトの値をテキストボックスに表示します。
textBox1.Text = dt.ToString("yyyy/MM/dd");
実行結果
プロジェクトを実行します。下図のウィンドウが表示されます。
[先月の月初の日付]ボタンをクリックします。テキストボックスに先月の月初の日付が表示されます。
先月の月初の日付を表すDateTimeオブジェクトが取得できました。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2020-08-10
作成日: 2020-08-07