How to handle date and time in C#?
There are many built-in classes and methods available in C# for handling dates and times. Here are some commonly used methods:
- Get the current date and time.
DateTime now = DateTime.Now;
- Format date and time:
string formattedDateTime = now.ToString("yyyy-MM-dd HH:mm:ss");
- Compare dates and times:
DateTime date1 = new DateTime(2022, 1, 1);
DateTime date2 = new DateTime(2022, 1, 2);
if (date1 < date2)
{
// do something
}
- Add or subtract time intervals.
DateTime newDate = now.AddHours(1);
DateTime newDate2 = now.AddDays(-1);
- Extract specific parts of date and time:
int year = now.Year;
int month = now.Month;
int day = now.Day;
int hour = now.Hour;
int minute = now.Minute;
int second = now.Second;
- Parse date and time strings:
string dateString = "2022-01-01";
DateTime parsedDate = DateTime.ParseExact(dateString, "yyyy-MM-dd", CultureInfo.InvariantCulture);
These are some commonly used methods for handling dates and times. In C#, there are many other methods and classes available for handling dates and times, the specific usage depends on your needs and circumstances.