How do I represent a time only value in .NET?
You can use timespan
TimeSpan timeSpan = new TimeSpan(2, 14, 18);
Console.WriteLine(timeSpan.ToString()); // Displays "02:14:18".
[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.
As others have said, you can use a DateTime
and ignore the date, or use a TimeSpan
. 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 the LocalTime
type to represent a time of day.
Note that as of .NET 6, there are TimeOnly
and DateOnly
types which are roughly equivalent to Noda Time's LocalTime
and LocalDate
types.
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.)