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:

  1. Get the current date and time.
DateTime now = DateTime.Now;
  1. Format date and time:
string formattedDateTime = now.ToString("yyyy-MM-dd HH:mm:ss");
  1. Compare dates and times:
DateTime date1 = new DateTime(2022, 1, 1);
DateTime date2 = new DateTime(2022, 1, 2);

if (date1 < date2)
{
    // do something
}
  1. Add or subtract time intervals.
DateTime newDate = now.AddHours(1);
DateTime newDate2 = now.AddDays(-1);
  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;
  1. 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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds