.net mvc 中@Html.DisplayFor 控制日期的显示格式

来源:互联网 发布:笑话源码 编辑:程序博客网 时间:2024/04/29 13:47

MVC中的@Html.DisplayFor等方法控制日期的显示格式:

在Sql Server2008中,如果将某字段定义成DateTime类型,那么在视图中会默认显示成年月日时分秒的方式(如:14/12/16 15:54:13)

如果只想显示成年月日形式,不要时分秒,那么该怎么办呢?

方法一:model类上面添加DisplayFormat的attribute,需要引用 usingSystem.ComponentModel.DataAnnotations;

[Display(Name = "发布时间:")][DisplayFormat(DataFormatString = "{0:yyyy年MM月dd日}")]public virtual System.DateTime CreateTime{ get; set;}

<span> @Html.DisplayFor(n => n.createTime) </span>
显示出来后,照样是2014年12月16日这种格式。


方法二:先设置一个时间显示的模板,然后在需要显示时间的地方调用这个模板就行了。

1、在Share文件夹下,创建一个文件夹DisplayTemplates

2、在DisplayTemplates文件夹下,创建一个视图DateTimeTemplate.cshtml

3、在视图DateTimeTemplate.cshtml中输入如下代码,当然,后面那句也可以换成@Model.ToShortDateString()或其它日期格式。

@model System.DateTime@Model.ToLongDateString()<!--时间格式模版 : DateTimeTemplate不用模版默认输出 : 14/12/9 15:54:13ToLongDateString() : 2014年12月9日ToShortDateString() : 14/12/9ToOADate() : 41982.6626600694ToLongTimeString() : 15:54:13等等...-->
4、在需要显示日期的地方,由原来的
<span> @Html.DisplayFor(n => n.createTime) </span>
替换成
<span>@Html.DisplayFor(n => n.createTime, "DateTimeTemplate")</span>

这样就完成了时间格式的显示转换。由原来的显示方式(14/12/16 15:54:13)显示成了(2014年12月16日)



如果不是强类型的,可以用这种方法:<td>@a.createTime.Value.ToString("yyyy-MM-dd hh:mm:ss")</td>

0 0
原创粉丝点击