どうも、ちょげ(@chogetarou)です。
DateTimeから現在時刻の文字列を取得する方法を紹介します。
方法

DateTimeから現在時刻の文字列を取得する方法は、3つあります。
ToString()
1つ目は、ToString()を使う方法です。
まず、DateTimeのNowプロパティにアクセスします。
そして、NowプロパティからToString()を呼び出します。
ToStringの引数に「h:mm:ss tt」の文字列を指定します。
string currentTime = DateTime.Now.ToString("h:mm:ss tt");
上記のToString()は、現在時刻の文字列を返します。
使用例
using System;
public class Example
{
public static void Main()
{
string currentTime = DateTime.Now.ToString("h:mm:ss tt");
Console.WriteLine(currentTime); //12:59:34 AM
}
}
ToLongTimeString()
2つ目は、ToLongTimeString()を使う方法です。
まず、DateTimeのNowプロパティにアクセスします。
そして、NowプロパティからToLongTimeString()を呼び出します。
string currentTime = DateTime.Now.ToLongTimeString();
上記のToLongTimeString()は、現在時刻の文字列を返します。
使用例
using System;
public class Example
{
public static void Main()
{
string currentTime = DateTime.Now.ToLongTimeString();
Console.WriteLine(currentTime); //1:08:31 AM
}
}
GetDateTimeFormats()
3つ目は、GetDateTimeFormats()を使う方法です。
まず、DateTimeのNowプロパティにアクセスします。
NowプロパティからGetDateTimeFormats()を呼び出します。
GetDateTimeFormats()の引数に「’T’」を指定します。
そして、GetDateTimeFormats()の末尾に[0]を記述します。
string currentTime = DateTime.Now.GetDateTimeFormats('T')[0];
上記のGetDateTimeFormats()は、現在時刻の文字列を返します。
使用例
using System;
public class Example
{
public static void Main()
{
string currentTime = DateTime.Now.GetDateTimeFormats('T')[0];
Console.WriteLine(currentTime); // 1:13:34 AM
}
}
まとめ
DateTimeから現在時刻の文字列を取得する方法は、次の3つです。
- ToString()を使う方法
string currentTime = DateTime.Now.ToString("h:mm:ss tt");
- ToLongTimeString()を使う方法
string currentTime = DateTime.Now.ToLongTimeString();
- GetDateTimeFormats()を使う方法
string currentTime = DateTime.Now.GetDateTimeFormats('T')[0];
コメント