Skip to main content

Working with Date and Time in C#

 In C#, the System.DateTime structure represents an instant in time, typically expressed as a date and time of day. You can use the DateTime structure to perform a variety of tasks, such as comparing dates, performing arithmetic with dates, and formatting dates for display.


Here are some examples of common tasks you might perform with DateTime in C#:


Getting the current date and time:

DateTime currentTime = DateTime.Now;



Creating a DateTime object for a specific date and time:

DateTime newYear = new DateTime(2022, 1, 1, 0, 0, 0);



Performing arithmetic with dates:

DateTime oneWeekFromNow = currentTime.AddDays(7);
DateTime oneWeekAgo = currentTime.AddDays(-7);



Comparing dates:

bool isNewYear = (newYear > currentTime);


Formatting dates for display:

string formattedDate = currentTime.ToString("MM/dd/yyyy HH:mm:ss");



There are many more features and capabilities of the DateTime structure in C#. You can find more information in the Microsoft documentation.

Comments