Date and Time Operations
Explore how to use C#'s DateTime struct to format dates and times flexibly, parse string inputs safely, and calculate durations with TimeSpan. Understand culture-specific formatting and modern string interpolation to display dates appropriately in your applications.
By default, when we print a DateTime object, it has a rigid and sometimes inconvenient format.
Line 1: We initialize a specific
DateTimeinstance.Line 2: We print the object directly to the console, which yields the default output format.
The default format often lacks the readability required for user-facing applications, but C# provides several ways to customize this output.
Note: The exact text output of DateTime heavily depends on the host system’s local culture settings. For example, a system in the US will print 12/24/2021, while a system in Europe will print 24/12/2021. The outputs shown in this lesson use the default US English culture.
Output format methods
The DateTime struct offers several output-formatting methods. Each provides a different representation of the data:
ToLocalTime(): This assumes the time inside theDateTimeobject is in UTC and converts it to local time.ToUniversalTime(): This assumes the time inside theDateTimeobject is in the local time zone and converts it to UTC.ToLongDateString(): This returns a string version of the date with the month written in words.ToShortDateString()...