Useful new .NET 6 features: DateOnly and TimeOnly structs
Posted: (EET/GMT+2)
.NET 6 introduced two small but very useful types: DateOnly and
TimeOnly. They make it easier to model values that are just a date or just a time,
without the extra "other part".
Before .NET 6, the usual approach was to use DateTime and ignore the unused
portion. That works, but it can lead to subtle bugs and unclear intent. These new structs make
the data shape explicit.
Let's take DateOnly first. It represents a calendar date without a time component:
DateOnly d = new DateOnly(2021, 11, 25); Console.WriteLine(d); Console.WriteLine(d.DayOfWeek); Console.WriteLine(d.AddDays(7));
This is useful for dates of birth, invoice due dates, and reporting periods where time of day is not relevant.
Similarly, the TimeOnly represents a time of day without a date:
TimeOnly t = new TimeOnly(14, 30, 0); Console.WriteLine(t); Console.WriteLine(t.AddMinutes(45));
Good fits include opening hours, daily schedules or recurring job times.
You can convert from existing DateTime values when needed:
DateTime now = DateTime.Now; DateOnly date = DateOnly.FromDateTime(now); TimeOnly time = TimeOnly.FromDateTime(now);
Both structs support parsing and formatting using the familiar patterns:
DateOnly d = DateOnly.Parse("2021-11-25");
TimeOnly t = TimeOnly.Parse("14:30");
string s = d.ToString("yyyy-MM-dd");
If your model only needs a date or a time, these types make the intent clearer and avoid carrying unused data around.
Happy date and time processing!