问题
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