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

DateTimeから今日の日付のみの文字列を取得する方法は、3つあります。
ToString()
1つ目は、ToString()を使う方法です。
まず、DateTimeのNowプロパティにアクセスします。
そして、NowプロパティからToString()を呼び出します。
ToStringの引数に「MM-dd-yyyy」の文字列を指定します。
string today = DateTime.Now.ToString("MM-dd-yyyy");
上記のToString()は、今日の日付のみの文字列を返します。
使用例
using System;
public class Example
{
public static void Main()
{
string today = DateTime.Now.ToString("MM-dd-yyyy");
Console.WriteLine(today); // 06-26-2022
}
}
ToShortDateString()
2つ目は、ToShortDateString()を使う方法です。
まず、DateTimeのNowプロパティにアクセスします。
そして、NowプロパティからToShortDateString()を呼び出します。
string today = DateTime.Now.ToShortDateString();
上記のToShortDateString()は、今日の日付のみの文字列を返します。
使用例
using System;
public class Example
{
public static void Main()
{
string today = DateTime.Now.ToShortDateString();
Console.WriteLine(today); // 6/26/2022
}
}
GetDateTimeFormats()
3つ目は、GetDateTimeFormats()を使う方法です。
まず、DateTimeのNowプロパティにアクセスします。
NowプロパティからGetDateTimeFormats()を呼び出します。
GetDateTimeFormats()の引数に「’d’」を指定します。
そして、GetDateTimeFormats()の末尾に[0]を記述します。
string today = DateTime.Now.GetDateTimeFormats('d')[0];
上記のGetDateTimeFormats()は、今日の日付のみの文字列を返します。
使用例
using System;
public class Example
{
public static void Main()
{
string today = DateTime.Now.GetDateTimeFormats('d')[0];
Console.WriteLine(today); // 6/27/2022
}
}
まとめ
DateTimeから今日の日付のみの文字列を取得する方法は、次の3つです。
- ToString()を使う方法
string today = DateTime.Now.ToString("MM-dd-yyyy");
- ToShortDateString()を使う方法
string today = DateTime.Now.ToShortDateString();
- GetDateTimeFormatsを使う方法
string today = DateTime.Now.GetDateTimeFormats('d')[0];
コメント