1

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

Tomas Grosup
  • 6,396
  • 3
  • 30
  • 44
  • You can use a data template for DateTime to achieve a similar effect. This would have a smaller impact than globally changing the Default Culture settings. – Aron Jul 30 '13 at 07:32

1 Answers1

4

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;
}
Peter Porfy
  • 8,921
  • 3
  • 31
  • 41
  • Thanks. Is there something I can do to switch the culture only for view rendering, and not for the rest of my server code? Is there an ActionFilter method matching this moment? – Tomas Grosup Jul 31 '13 at 08:30
  • 1
    There is no such a built in actionfilter as far as I know but you can easly create one: http://msdn.microsoft.com/en-us/library/system.web.mvc.actionfilterattribute(v=vs.108).aspx you can save the current culture within OnResultExecuting and switch to the new one and you can change it back within OnResultExecuted. – Peter Porfy Jul 31 '13 at 10:29