如何格式化在asp.net的MVC 5日 [英] How to format date in asp.net mvc 5

查看:102
本文介绍了如何格式化在asp.net的MVC 5日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过在模型类设置,但没有得到期望的结果在asp.net MVC 5格式化日期。请查看下面的日期:

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

10/10/2010 12:00:00 AM

我想改变上述日期的格式如下: -

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

OCT-10-2014

OCT-10-2014

请查看下面

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

以上code未在要求的格式格式化。还可以查看我的code低于呈现类似下面的表格。

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>

所以我也试过code下面这仍然是行不通的。

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

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

请在我的code如果缺少IAM纠正amything,由于

Please correct if iam missing amything in my code, thanks

推荐答案

首先应用 DisplayFormat 属性 [DisplayFormat(DataFormatString ={0: MMM-DD-YYYY}仅当您使用的工作 @ Html.DisplayFor() @ Html.Display ()帮手。所以,你可以用

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>

请注意,您可能还需要使用 NullDisplayText =someValue中如果适用

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

第二, DATEOFBIRTH 可为空,所以如果你不使用的助手,那么 DateOfBirth.ToString(MMM / DD / YYYY)

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>

这篇关于如何格式化在asp.net的MVC 5日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆