使用数据注释分配DateTime的格式?

115

我在我的视图模型中有这个属性:

[DataType(DataType.DateTime)]
public DateTime? StartDate { get; set; }

如果我想显示日期,或者用日期填充文本框,我有以下选项:

<%: Model.StartDate %>

<%: Html.TextBoxFor(m => m.StartDate) %>
每当显示日期时,它都会显示为:01/01/2011 12:00:00 AM 但我想仅显示01/01/2011 有没有一种方法可以使用数据注释来应用显示格式?我不想去每个显示日期的实例中,添加一些代码来进行格式化。

4
重复的问题?https://dev59.com/7HI-5IYBdhLWcg3wN1lD该问题的意思是如何从TextBoxFor中仅获取日期。 - David Fox
11个回答

170

尝试使用标签进行标记:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]

1
刚试了一下,它仍然在文本框中显示时间,并且当它只是在页面上显示时也是如此。 - Steven
3
@Steven:如果你还没有尝试过,请尝试移除[DataType(DataType.DateTime)] - David Fox
12
DisplayFormat 仅与 EditorForDisplayFor 帮助器一起使用。 - Ε Г И І И О
1
很棒的答案 - 我漏掉了“ApplyFormatInEditMode”参数。 - CodeHxr
6
我可以通过Html.TextBoxFor中的format参数来解决这个问题。 通过将其设置为@Html.TextBoxFor(model => model.YOUR_DATE, "{0:MM/dd/yyyy}"),我能够仅显示日期。 在此处找到 [https://dev59.com/VnI95IYBdhLWcg3w7SpZ#14529347]。 - Caffeinius
显示剩余2条评论

60

你试过这个了吗?

[DataType(DataType.Date)]

3
如果浏览器支持,这将使HTML5日期选择器得到支持。 - AaronLS

27

在 MVC 4 中,您可以轻松使用 TextBoxFor 来执行以下操作...

@Html.TextBoxFor(m => m.StartDate, "{0:MM/dd/yyyy}", new { @class = "form-control default-date-picker" })
所以,在模型或视图模型类中,您不需要使用任何数据注释。

是的,那些DataAnnotations在EditorFor助手中非常好用,但是当使用IEnumerable(Of Entity)渲染自定义网格时,您必须使用.TextBoxFor,这就是我的问题所在。谢谢。 - bkwdesign

23
如果您的数据字段已经是DateTime数据类型,则无需使用[DataType(DataType.Date)]进行注释;只需使用以下内容即可:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]

使用jQuery的datepicker插件来创建日历

    $(document).ready(function () {
        $('#StartDate').datepicker();
    });

在您的HTML中,使用EditorFor助手:

    @Html.EditorFor(model => model.StartDate)

如果您的数据字段已经是DateTime数据类型,那么您就不需要使用[DataType(DataType.Date)]。这很有帮助。 - MD TAREQ HASSAN
但对于Web API来说,显示格式并没有强制执行DataFormatString = "{0:MM/dd/yyyy}"(即使请求体具有其他格式,例如{"dob":"31/12/1990"}),也没有收到任何400错误。 - MD TAREQ HASSAN

19

应用数据注释,如下所示:

[DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}")]

13

使用这个,但这是一种完整的解决方案:

[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]

7
这对我来说可以。
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]

ApplyFormatInEditMode就是解决方案!谢谢。 - Axel Samyn

5

4

使用EditorFor而不是TextBoxFor


2
这是我最喜欢的使用模型注释完成的方法:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyy}")]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接