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

DateTimeから月のみを取得する方法は、2つあります。
Monthプロパティ
1つは、Monthプロパティを使う方法です。
具体的な方法としては、date.Month
のように、DateTimeのMonthプロパティにアクセスします。
int month = date.Month;
上記のMonthは、アクセス元のDateTimeの月を数値として取得します。
使用例
using System;
public class Example
{
public static void Main()
{
DateTime currentDate = DateTime.Now;
int month = currentDate.Month;
Console.WriteLine(currentDate);
Console.WriteLine(month);
}
}
出力:
7/21/2022 11:52:12 PM
7
ToString()
もう1つは、ToString()を使う方法です。
まず、DateTimeからToString()を呼び出します。
そして、ToSting()の引数の文字列内に、次のいずれかのフォーマットを指定します。
- M : 月を1桁で取得
例)7/21/2022 11:52:12 PM -> 7 - MM : 月を2桁で取得(1桁の月は0埋め)
例)7/21/2022 11:52:12 PM -> 07 - MMM : 月を名前の略称で取得
例)7/21/2022 11:52:12 PM -> Jul - MMMM : 月を名前の略称で取得
例)7/21/2022 11:52:12 PM -> July
string result = date.ToString("フォーマット");
上記のToString()は、呼び出したDateTimeの月のみを文字列として取得します。
使用例
using System;
public class Example
{
public static void Main()
{
DateTime date = new DateTime(2022, 7, 22);
string result = date.ToString(" M");
string result2 = date.ToString("MM");
string result3 = date.ToString("MMM");
string result4 = date.ToString("MMMM");
Console.WriteLine(result);
Console.WriteLine(result2);
Console.WriteLine(result3);
Console.WriteLine(result4);
}
}
出力:
7
07
Jul
July
まとめ
DateTimeから月のみを取得する方法は、次の2つです。
- Monthプロパティを使う方法
int month = date.Month;
- ToString()を使う方法
string result = date.ToString("フォーマット");
コメント