Is there a way one can represent a time only value in .NET without the date? For example, indicating the opening time of a shop?
TimeSpan
indicates a range, whereas I only want to store a time value. Using DateTime
to indicate this would result in new DateTime(1,1,1,8,30,0)
which is not really desirable.
As others have said, you can use a
DateTime
and ignore the date, or use aTimeSpan
. Personally I'm not keen on either of these solutions, as neither type really reflects the concept you're trying to represent - I regard the date/time types in .NET as somewhat on the sparse side which is one of the reasons I started Noda Time. In Noda Time, you can use theLocalTime
type to represent a time of day.One thing to consider: the time of day is not necessarily the length of time since midnight on the same day...
(As another aside, if you're also wanting to represent a closing time of a shop, you may find that you want to represent 24:00, i.e. the time at the end of the day. Most date/time APIs - including Noda Time - don't allow that to be represented as a time-of-day value.)
If that empty
Date
really bugs you, you can also to create a simplerTime
structure:Or, why to bother: if you don't need to do any calculation with that information, just store it as
String
.You can use timespan
[Edit]
Considering the other answers and the edit to the question, I would still use TimeSpan. No point in creating a new structure where an existing one from the framework suffice.
On these lines you would end up duplicating many native data types.
I think Rubens' class is a good idea so thought to make an immutable sample of his Time class with basic validation.
Here's a full featured TimeOfDay class.
This is overkill for simple cases, but if you need more advanced functionality like I did, this may help.
It can handle the corner cases, some basic math, comparisons, interaction with DateTime, parsing, etc.
Below is the source code for the TimeOfDay class. You can see usage examples and learn more here:
This class uses DateTime for most of its internal calculations and comparisons so that we can leverage all of the knowledge already embedded in DateTime.
In addition to Chibueze Opata: