TimeOnly
was one of the new types introduced with .Net 6 along with DateOnly
. I understand the great need for the DateOnly
type as there are many instances you would want to store a date without a related time but no data type that did so.
However, in regards to time, TimeSpan
already exists and is capable of representing times. Timespan
very similar to TimeOnly
except, TimeOnly
seems to have a few properties missed.
Is there any great benefit offered from using TimeOnly
instead of TimeSpan
apart from saving a bit a memory?
One of the benefits I can see from using TimeOnly
instead of TimeSpan
is in having appropriate data types to represent periods of time vs times of the day.
TimeOnly
is better suited for times of day and TimeSpan
is better suited for representing durations/periods of time. It also has methods that correctly handle additions/subtractions to times that cross over midnight unlike TimeSpan
e.g. 23:00 + 2hrs would equal 01:00 (with TimeOnly
).
TimeOnly
only allows you to modify it in ways that will produce a valid time of day but TimeSpan
allows modifications that could result in a value that is out of range.
TimeSpan
can represent a larger range of time periods (including negative periods of time), it has a range of about +/- 29,000 years whereas TimeOnly
can only represent 00:00:00.0000000 to 23:59:59.9999999.
The following blog post provides more info on the TimeOnly
type (as well as DateOnly
): https://devblogs.microsoft.com/dotnet/date-time-and-time-zone-enhancements-in-net-6/