C#で時間を取得する方法はどれですか?
C#で時間を取得する方法はいくつかあります。
- DateTimeクラスの静的メソッドNowを使用して、現在のシステム時間を取得します。
DateTime currentTime = DateTime.Now;
- DateTimeクラスの静的メソッドUtcNowを使用して、現在のシステムのUTC時間を取得します。
DateTime currentUtcTime = DateTime.UtcNow;
- DateTimeクラスのコンストラクタを使用して指定した時間を作成する。
DateTime specifiedTime = new DateTime(2022, 12, 31, 23, 59, 59);
- DateTimeクラスのプロパティを使用して特定の時間情報を取得すると、年、月、日、時間、分などが取得できます。
int year = currentTime.Year;
int month = currentTime.Month;
int day = currentTime.Day;
int hour = currentTime.Hour;
int minute = currentTime.Minute;
- DateTimeクラスのToStringメソッドを使用して、時間を特定の文字列形式にフォーマットします。
string formattedTime = currentTime.ToString("yyyy-MM-dd HH:mm:ss");
C#で時間を取得するための一般的な方法です。開発中は、具体的な要件に応じて適切な方法を選択して時間情報を取得します。