What Benefits Does TimeOnly Have Over TimeSpan?
Asked Answered
D

1

13

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?

Delwin answered 30/6, 2022 at 13:26 Comment(4)
Does this answer your question? How do I represent a time only value in .NET?Countryside
This concern of the question is the benefits of TimeOnly vs TimeSpan not just how to represent Time.Delwin
Note that a difference between TimeOnly is always positive and can be confusing #73040186Grubb
@MichaelFreidgeim true - I did mention in my answer, that TimeSpan has a range of approx +/- 29,000 years and that TimeOnly can only represent times on a 24hr clock.Delwin
D
16

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 TimeOnlycan 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/

Delwin answered 30/6, 2022 at 13:26 Comment(2)
How is a lot of space saved if they're both represented internally a long?During
@During you're right, they are both just 8 bytes.Delwin

© 2022 - 2024 — McMap. All rights reserved.