How to use datetime in C#?

In C#, the DateTime class can be used to handle dates and times. Here are some common ways to use DateTime:

  1. Create an instance of the current date and time.
DateTime now = DateTime.Now;
  1. Create an instance with a specified date and time:
DateTime date = new DateTime(2021, 9, 30);
DateTime dateTime = new DateTime(2021, 9, 30, 10, 30, 0);
  1. Retrieve various components of the 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. Format the date and time into a string.
string formattedDate = now.ToString("yyyy-MM-dd");
string formattedDateTime = now.ToString("yyyy-MM-dd HH:mm:ss");
  1. Calculate dates and times.
DateTime tomorrow = now.AddDays(1);
DateTime nextWeek = now.AddDays(7);
DateTime oneHourLater = now.AddHours(1);
DateTime oneMinuteAgo = now.AddMinutes(-1);
  1. Compare dates and times:
bool isSameDate = now.Date == date.Date;
bool isBefore = now < dateTime;
bool isAfter = now > dateTime;

This is just some basic usage of the DateTime class, you can explore more related usage and functionalities by referring to the C# official documentation or other resources.

bannerAds