Tomas Grosup
Tomas Grosup

Reputation: 6514

Change default DateTime format for razor

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>.

Upvotes: 1

Views: 1974

Answers (1)

Peter Porfy
Peter Porfy

Reputation: 9030

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;
}

Upvotes: 4

Related Questions