How to save time only without the date using ASP.NET MVC 5 Data Annotation "DataType.Time?
14,298
Solution 1
In that case you need to store that as a string. You cannot separate Time
from Date
using BCL (Base Class Library) of .Net. They cannot exist as independent entities.
However youcan have a workaround to save Time in a TimeSpan
object using this Representing Time (not date and time) in C#
Solution 2
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
public DateTime Hour { get; set; }
Author by
TJ Riceball
Updated on June 27, 2022Comments
-
TJ Riceball over 1 year
My Model Class looks like this:
[DataType(DataType.Time)] public DateTime Time {get; set;}
When I run it, I have a cool an HTML 5 Input Type in Time. When I save the data, the value in my database looks like this:
7/11/2014 1:00AM
It automatically saves the current date. I just wanna have the time saved. I'm trying to create a reservation system.
-
Jon Skeet over 9 yearsThey certainly can exist as independent entities. They happen not to in the BCL, but they do in databases, and do in other libraries too...
-
Nikhil Agrawal over 9 years@JonSkeet: I am talking about .Net.
-
Jon Skeet over 9 yearsWell again, that can be done in libraries in .NET - my Noda Time library separates them. If you mean to say "The BCL doesn't provide separate time and date types" then that's what you should have said... which is very different from what you're actually said.
-
Jon Skeet over 9 yearsUsing a string to store date/time values in a database is a really bad idea. Databases do (generally) have separate date and time types, and that's the better solution.
-
Jon Skeet over 9 yearsAnd to be generally sane. It's a shame we have no idea where the OP is storing the data. If it's in SQL Server 2008+, then a
TIME
field is the most appropriate... -
Arijit Mukherjee over 9 years@JonSkeet Seeking feedback for my answer as well :)
-
Jon Skeet over 9 yearsWell, I'd say that it doesn't really address the question, which is about storing the data... and if the OP is using an appropriate database, then they can use a
TIME
field. In terms of "within the C# code" I'd advocate using Noda Time, of course :)