どうも、ちょげ(@chogetarou)です。
DateTimeで今月の月初を取得する方法を紹介します。
方法

DateTimeで今月の月初を取得するには、DateTime()を使います。
まず、new DateTime()
のように、DateTimeをインスタンス化します。
インスタンス化する際、DateTime()の第1引数にDateTime.NowのYearプロパティ、第2引数にDateTime.NowのMonthプロパティを指定します。
そして、DateTimeの第3引数に「1」を指定します。
DateTime result = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
上記のDateTime()は、今月の月初のDateTimeを生成します。
使用例
using System;
public class Example
{
public static void Main()
{
DateTime currentDate = DateTime.Now;
DateTime result = new DateTime(currentDate.Year, currentDate.Month, 1);
Console.WriteLine(currentDate);
Console.WriteLine(result);
}
}
出力:
7/22/2022 12:33:54 AM
7/1/2022 12:00:00 AM
コメント