C# サンプル集 |
Visual Basic 中学校 > C# サンプル集 > C# サンプル集目次 >
月末を求める
2020/7/19
2024年2月の月末の 日付 を取得する
//まず月の始めの1日の日付を作成する。 DateTime firstDate = new DateTime(2024, 2, 1); //1ヶ月後の1日前を求める DateTime lastDate = firstDate.AddMonths(1).AddDays(-1); System.Diagnostics.Debug.WriteLine(lastDate.ToString(@"yyyy\/MM\/dd")); // 2024/02/29 と表示されます。 |
2024年2月の月末が 何日か を取得する
int lastDay =
DateTime.DaysInMonth(2024,
2); System.Diagnostics.Debug.WriteLine(lastDay); //29 と表示されます。 |
月末を返す関数
次の関数は引数に渡された日付の月末の日付を返します。
/// <summary> /// targetDateで指定した月の月末の日付を求めます。 /// targetDateに時刻を含む場合、時刻は0:00:00になります。 /// </summary> public DateTime GetEndOfMonth(DateTime targetDate) { //まず月の始めの1日の日付を作成する。 DateTime firstDate = new DateTime(targetDate.Year, targetDate.Month, 1); //1ヶ月後の1日前を求める DateTime lastDate = firstDate.AddMonths(1).AddDays(-1); return lastDate; } |
呼び出し例
DateTime theDate
= new
DateTime(2024, 6,
27); DateTime lastDate = GetEndOfMonth(theDate); System.Diagnostics.Debug.WriteLine(lastDate.ToString(@"yyyy\/MM\/dd")); //2024/06/30 と表示されます。 |