asp.net mvc格式在整个应用程序中的DateTime

时间:2014-01-30 09:29:35

标签: asp.net-mvc datetime-format

基本上,我想要的是在整个应用程序中格式化DateTime并在整个Web应用程序中以特定格式显示它。有没有更好的解决方案来写ToString("{0:stringformathere}", obj)

2 个答案:

答案 0 :(得分:1)

尝试覆盖网页的InitializeCulture方法。

Thread.CurrentThread.CurrentCulture = <some custom culture>

http://msdn.microsoft.com/en-us/library/bz9tc508.aspx

答案 1 :(得分:0)

您可以创建自己的编辑/显示模板,并在整个应用程序中重复使用。

查看/共享/ EditorTemplates / CustomDateTime.cshtml

@model DateTime?
@{
    String modelValue = "";
    var dateFormatToDisplay =
       System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern;

    if (Model.HasValue)
    {
        if (Model.Value != DateTime.MinValue)
        {
            modelValue = Model.Value.ToString(dateFormatToDisplay);
        }
    }
}

@Html.TextBox("", modelValue)

在视图中

@Html.EditorFor(m => m.DateOfBirth, "CustomDateTime")