C-SHARP - 6.2 DateTime
The DateTime structure in C# is the entry point for representing and working with precise points in time. An instance encapsulates both a date (day, month, year) and a time (hour, minute, second, millisecond), with enough precision for the everyday needs of professional applications. You reach for it whenever you need to timestamp an event, record when a resource was created, or calculate an age.
You can create a DateTime several ways: an explicit constructor with the individual components, the DateTime.Now or DateTime.UtcNow properties, or by parsing a string with DateTime.Parse or DateTime.TryParse. This last form is recommended when the data comes from user input or an external file, since it handles invalid values cleanly without throwing an exception.
Once an instance exists, you access its components through the Year, Month, Day, Hour, Minute, and Second properties. Arithmetic is done through methods like AddDays, AddHours, AddMonths and their equivalents, which return a new instance instead of modifying the existing one: DateTime is immutable, which makes it safe to use in code shared across threads.
Display formatting relies on the ToString method with a standard or custom format string: "d" for the short date, "D" for the long date, "yyyy-MM-dd HH:mm:ss" for a readable ISO format. For more advanced cases (durations, explicit time offsets, time zones), the language provides the complementary TimeSpan and DateTimeOffset types, covered in the next lessons of this section.