DateOnly and TimeOnly

Learn how to represent and manipulate dates and times independently using the DateOnly and TimeOnly structs.

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.