zoukankan      html  css  js  c++  java
  • MVC中的@Html.DisplayFor等方法如何控制日期的显示格式(转)

    http://www.tuicool.com/articles/BNVBR3

    在Sql Server2005中,如果将某字段定义成日期 时间 类型DateTime,那么在视图中会默认显示成年月日时分秒的方式(如  2013/8/6 13:37:33)

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

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

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

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

    3、在视图LongDateTime.cshtml中输入代码

    @model System.DateTime
    
    @Model.ToLongDateString()

    当然,后面那句也可以换成@Model.ToShortDateString()或其它日期格式。

    4、在需要显示日期的地方,由原来的

    @Html.DisplayFor(modelItem => item.PostTime)

    替换成

    @Html.DisplayFor(modelItem => item.PostTime,"LongDateTime")

    这样就完成了时间格式的显示转换。由原来的显示方式(2013/8/6 13:37:33)显示成了(2013年8月6日)

    第二种方法:model类上面添加DisplayFormat的attribute.

    如:

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

    显示出来后,照样是2013年8月6日这种格式。

  • 相关阅读:
    java中的工厂模式(简单工厂模式+工厂方法模式)
    代码集合
    java读取文件的路径问题
    使用ZXing库生成二维码
    java设计模式-装饰者模式
    android文件流缓存
    java8 新特性
    Excel导出
    常用的在线工具
    Java加密简介
  • 原文地址:https://www.cnblogs.com/Rising/p/3722299.html
Copyright © 2011-2022 走看看