无法在 MVC 5 中正确格式化日期

Unable to format date correctly in MVC 5

我的模型属性是这样的

    [DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}"), DisplayName("Procedure Effective From"),
     DataType(DataType.Date)]
    public DateTime ProcedureEffectiveFrom { get; set; }

并且在视图中

     @Html.TextBoxFor(model => model.ProcedureEffectiveFrom, new { @class = "form-control date-picker" })
  @Html.ValidationMessageFor(model => model.ProcedureEffectiveFrom)

我期待这样的输出

1/27/2015

但是输出是

1/27/2015 10:40:45 AM

谁能指出我做错了什么?

只有在使用 @Html.DisplayFor()@Html.EditorFor() 时才尊重 [DisplayFormat][DataType]。您需要使用接受格式字符串的重载来设置格式。

@Html.TextBoxFor(m => m.ProcedureEffectiveFrom, "{0:MM dd, yyyy}" new { @class = "form-control date-picker" })

使用它

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MMM dd, yyyy}"),DisplayName("Procedure Effective From")]
      public DateTime ProcedureEffectiveFrom { get; set; }

在视图中使用喜欢

 @Html.EditorFor(model => model.ProcedureEffectiveFrom, new { @class = "form-control date-picker" })
@Html.ValidationMessageFor(model => model.ProcedureEffectiveFrom)

显示日期时间使用

  @Html.DisplayFor(model => model.ProcedureEffectiveFrom)

正在查看你可以试试这个。

@Html.TextBoxFor(m => m.ProcedureEffectiveFrom, new { htmlAttributes = new { @Value = m.ProcedureEffectiveFrom.ToString("MM/dd/yyyy"), @class = "form-control" } })