How to format date in asp.net mvc 5

强颜欢笑 提交于 2019-12-11 07:44:47

问题


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>


来源:https://stackoverflow.com/questions/26311134/how-to-format-date-in-asp-net-mvc-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!