DateOnly and TimeOnly
Explore how C#'s DateOnly and TimeOnly structs allow you to manage dates and times separately without time zone issues. Understand their syntax, methods for manipulation, and how to extract or combine these structs with DateTime. This lesson helps you write precise and reliable date and time handling code in .NET applications.
The DateTime struct effectively represents an exact point in time, but many applications only need to track a specific date or time of day independently. Developers historically used DateTime for these scenarios and ignored the unused components. Relying on DateTime for date-only data often causes bugs when applications move data across different time zones.
Modern .NET provides the DateOnly and TimeOnly structs to solve this problem. Because the new types lack time zone data, they prevent time zone shifting bugs. DateOnly also consumes less memory, and both map directly to database types like SQL Server’s DATE and TIME.
DateOnly syntax
We can initialize a DateOnly value using a constructor that takes the year, month, and day. We can also extract a DateOnly directly from an existing DateTime object.
Lines 1–3: We define integer variables representing the year, month, and day.
Line 5: We create a new
DateOnly...