Light Mode Image

C# DateTime

DateTime in C# is used to represent dates and times. It is part of the System namespace. Here are some common operations and examples of using DateTime in C#.

 

Creating a DateTime instance

DateTime now = DateTime.Now; // current date and time
DateTime today = DateTime.Today; // current date with time set to midnight
DateTime specificDate = new DateTime(2023, 12, 26); // specific date and time

 

Formatting DateTime to string

string formattedDate = now.ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine(formattedDate);

 

Accessing individual components

int year = now.Year;
int month = now.Month;
int day = now.Day;
int hour = now.Hour;
int minute = now.Minute;
int second = now.Second;

 

Adding or subtracting time

DateTime futureDate = now.AddHours(24); // add 24 hours
DateTime pastDate = now.AddMonths(-1); // subtract 1 month

 

Comparing DateTime instances

DateTime anotherDate = new DateTime(2023, 12, 25);
if (now > anotherDate)
{
    Console.WriteLine("Now is later than anotherDate");
}

 

Parsing a string to DateTime

string dateStr = "2023-12-26";
DateTime parsedDate = DateTime.ParseExact(dateStr, "yyyy-MM-dd", CultureInfo.InvariantCulture);

 

TimeSpan for duration

DateTime start = DateTime.Now;
// Some operation or delay
DateTime end = DateTime.Now;
TimeSpan duration = end - start;
Console.WriteLine($"Duration: {duration.TotalSeconds} seconds");

 

Depending on your use case, you might need more advanced functionalities, such as working with time zones for better representation of dates and times.