Change default DateTime format for razor

冷暖自知 提交于 2020-01-05 05:52:52

问题


Is there a way I can change the default formatting for all DateTime objects to e.g. "dd.MM.yyyy" in Razor ?

I would like to cover cases when a programmer forgets to call an extension method or to pass a format string, i.e. <p>@Model.MyDateTimeObject</p>.


回答1:


There is no thing like default formatting in Razor. When you do this: <p>@Model.MyDateTimeObject</p> Razor will simply use the default DateTime.ToString overload to print the date.

This works by the actual culture information, so for example if you want your example as the default ToString behavior then you should change the current culture for the actual request. E.g. in global.asax:

protected void Application_BeginRequest()
{
    CultureInfo culture = (CultureInfo)CultureInfo.InvariantCulture.Clone();
    culture.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
    culture.DateTimeFormat.LongTimePattern = "";
    Thread.CurrentThread.CurrentCulture = culture;
}


来源:https://stackoverflow.com/questions/17940403/change-default-datetime-format-for-razor

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