How do I represent a time only value in .NET?

2020-01-25 04:09发布

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.

8条回答
【Aperson】
2楼-- · 2020-01-25 04:46

If you don't want to use a DateTime or TimeSpan, and just want to store the time of day, you could just store the seconds since midnight in an Int32, or (if you don't even want seconds) the minutes since midnight would fit into an Int16. It would be trivial to write the few methods required to access the Hour, Minute and Second from such a value.

The only reason I can think of to avoid DateTime/TimeSpan would be if the size of the structure is critical.

(Of course, if you use a simple scheme like the above wrapped in a class, then it would also be trivial to replace the storage with a TimeSpan in future if you suddenly realise that would give you an advantage)

查看更多
叛逆
3楼-- · 2020-01-25 04:48

I say use a DateTime. If you don't need the date portion, just ignore it. If you need to display just the time to the user, output it formatted to the user like this:

DateTime.Now.ToString("t");  // outputs 10:00 PM

It seems like all the extra work of making a new class or even using a TimeSpan is unnecessary.

查看更多
登录 后发表回答