Change default DateTime format for razor

2019-07-28 04:28发布

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条回答
倾城 Initia
2楼-- · 2019-07-28 05:10

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;
}
查看更多
登录 后发表回答