简体   繁体   English

如何使用ASP.NET MVC 5数据注释“DataType.Time?”仅在没有日期的情况下节省时间

[英]How to save time only without the date using ASP.NET MVC 5 Data Annotation "DataType.Time?

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. 当我运行它时,我有一个很酷的HTML 5输入类型的时间。 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. 我正在尝试创建一个预订系统。

[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
public DateTime Hour { get; set; }

In that case you need to store that as a string. 在这种情况下,您需要将其存储为字符串。 You cannot separate Time from Date using BCL (Base Class Library) of .Net. 您不能使用.Net的BCL(基类库)将TimeDate分开。 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# 但是,您可以使用C#中的表示时间(而不是日期和时间)在 TimeSpan对象中保存Time的解决方法

Similar question gives a series of answers you might like, How do I represent a time only value in .NET? 类似的问题提供了一些您可能喜欢的答案, 我如何在.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 然而,最重要的问题是你应该在数据库中设置什么类型的时间,这个问题在数据库中存储时间(hh:mm)的最佳方法提供了更多

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中的字符串表示,但请阅读其他问题和答案,您可能希望以字符串以外的格式保存,以便更轻松地评估查询...

DateTime.Now.ToString("t");
[DisplayFormat(DataFormatString = "{0:t}")]
public DateTime Time {get; set;}

will display only the time 将只显示时间

For reference Follow : 供参考遵循:

MSDN Reference MSDN参考

只需将数据类型更改为数据库中的字符串,即可节省时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM