C#でのdatetimeの使い方は?
C#では、DateTimeクラスを使用して日付と時刻を操作することができます。以下は一般的なDateTimeの使用例です:
- 現在の日付と時刻のインスタンスを作成します。
DateTime now = DateTime.Now;
- 指定された日付と時間のインスタンスを作成します。
DateTime date = new DateTime(2021, 9, 30);
DateTime dateTime = new DateTime(2021, 9, 30, 10, 30, 0);
- 日付と時間の各部分を取得します。
int year = now.Year;
int month = now.Month;
int day = now.Day;
int hour = now.Hour;
int minute = now.Minute;
int second = now.Second;
- 日付と時間を文字列に変換する:
string formattedDate = now.ToString("yyyy-MM-dd");
string formattedDateTime = now.ToString("yyyy-MM-dd HH:mm:ss");
- 日付と時間の計算を行う。
DateTime tomorrow = now.AddDays(1);
DateTime nextWeek = now.AddDays(7);
DateTime oneHourLater = now.AddHours(1);
DateTime oneMinuteAgo = now.AddMinutes(-1);
- 日付と時間を比較する:
bool isSameDate = now.Date == date.Date;
bool isBefore = now < dateTime;
bool isAfter = now > dateTime;
これはDateTimeクラスの基本的な使用方法に過ぎないので、C#公式ドキュメントや他のリソースを参照してさらなる関連する使用方法や機能を理解することができます。