3

I'm trying to get cultural specific data annotations.

[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime Date{ get; set; }

I thought this would work. So in the us it would show DD/MM/yyyy and in europe it would show MM/DD/YYYY.

To test this, I set my default chrome language to English (UK) and restarted the browser.

I'm still getting the US format though, which leads me to believe my DataFormatString isn't respecting cultures.

How to I fix this? Can I also cut of the year so it's just "yy" instead of "yyyy"?

Nate
  • 2,316
  • 4
  • 35
  • 53

2 Answers2

4

This format is culture specific. You must be doing something wrong.

  1. Create a new ASP.NET MVC application using the default template
  2. Add a view model:

    public class MyViewModel
    {
        [DisplayFormat(DataFormatString = "{0:d}")]
        public DateTime Date { get; set; }
    }
    
  3. A controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel
            {
                Date = DateTime.Now,
            });
        }
    }
    
  4. And a view:

    @using MvcApplication1.Models
    @model MyViewModel
    
    @Html.DisplayFor(x => x.Date)
    

Now force the culture in your web.config to some specific culture:

<system.web>
    <globalization culture="fr-FR"/>
    ...
</system.web>

enter image description here

So make sure you set the culture to auto in this case:

<system.web>
    <globalization culture="auto"/>
    ...
</system.web>

Then the browser will send the proper Accept-Language request header that looks like this:

enter image description here

and obviously the result will be formatted as expected:

enter image description here

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2

You have to actually set the current culture, the MVC framework doesn't set it automatically (remember that a page's language might depend on factors like the URL, not just the browser settings.

To set the culture, use Thread.CurrentThread.CurrentCulture and Thread.CurrentThread.CurrentUICulture. You can get the browser settings from HttpRequest.UserLanguages (keep in mind that this value is just what comes through the HTTP request).

Edit

Per this answer, it seems there is a way to instruct ASP.Net to set the language based on the HTTP request header (set web.config globalization -> "culture" and "uiCulture" to "auto").

Community
  • 1
  • 1
McGarnagle
  • 101,349
  • 31
  • 229
  • 260