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
DateTimeand 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 theLocalTimetype to represent a time of day.Note that as of .NET 6, there are
TimeOnlyandDateOnlytypes which are roughly equivalent to Noda Time’sLocalTimeandLocalDatetypes.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.)