问题
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.
回答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#
回答2:
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
public DateTime Hour { get; set; }
回答3:
Similar question gives a series of answers you might like, How do I represent a time only value in .NET? but the
However the overriding question is what type you should set the time to in your db, and this question Best way to store time (hh:mm) in a database gives more
The following will give you a string representation from your DateTime, but read the other questions and answers, and you might want to save in a format other than string to make it easier to evaluate queries...
DateTime.Now.ToString("t");
回答4:
[DisplayFormat(DataFormatString = "{0:t}")]
public DateTime Time {get; set;}
will display only the time
For reference Follow :
MSDN Reference
回答5:
Just change the data type as as string in database then you can save your time.
来源:https://stackoverflow.com/questions/24693572/how-to-save-time-only-without-the-date-using-asp-net-mvc-5-data-annotation-data