How to format date in asp.net mvc 5

2019-08-04 19:35发布

问题:

I am trying to format a date in asp.net MVC 5 by setting in a model class but not getting the desired result. Please view the date below:

10/10/2010 12:00:00 AM

I want to change the above date in the following format:-

OCT-10-2014

Please view my model class below

[DisplayFormat(DataFormatString = "{0:MMM-dd-yyyy}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "Date is required")]
 public DateTime? DateOfBirth { get; set; }

The above code is not formatting in the required format . Also view my code below which render like a table below.

foreach (var m in Model)
            {
                <tr style="height: 22px; border-bottom: 1px solid silver">
                    <td style="width: 150px">@m.StudentId</td>
                    <td style="width: 150px">@m.FirstName</td>
                    <td style="width: 150px">@m.LastName</td>
                    <td style="width: 150px">@m.DateOfBirth</td>
                </tr>

So i also tried the code below which is still not working.

<td style="width: 150px">@m.DateOfBirth.ToString("MMM/dd/yyyy")</td>

Please correct if iam missing amything in my code, thanks

回答1:

Firstly applying the DisplayFormat attribute [DisplayFormat(DataFormatString = "{0:MMM-dd-yyyy}" only works if you use the @Html.DisplayFor() or @Html.Display() helper. So you can use

<td style="width: 150px">@Html.DisplayFor(model => m.DateOfBirth)</td>

Note, you may want to also use NullDisplayText="SomeValue" if applicable

Secondly, DateOfBirth is nullable so if you do not use the helper then DateOfBirth.ToString("MMM/dd/yyyy") should be

<td style="width: 150px">@(Model.DateOfBirth.HasValue ? Model.DateOfBirth.Value.ToString("MMM-dd-yyyy") : "SomeValue")</td>