Vinyl Warmth Vinyl Warmth -4 years ago 61
C# Question

Why are the dates in my MVC app in the wrong format?

I have an MVC5 application running in Azure and would like dates to be shown in UK format, such as:

15/12/16

but they always come out in this format:

12/15/16

I have set the culture in

system.web
in
Web.config
to

<globalization culture="en-GB" uiCulture="en-GB" />


I know this comes down to me not understanding globalization / culture in ASP.NET but I'm finding the official documentation to be really poor.

I've spent hours going round in circles trying to figure out how to do this, can anyone show me what I'm doing wrong?

Answer Source

One Solution

You could set the culture in the global.asax.cs file, like so:

// using System.Globalization;

protected void Application_Start()
{
    // Formatting numbers, dates, etc.
    CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-GB");

    // UI strings that we have localized.
    CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("en-GB");
}

Debugging

You can use this to check your culture:

Thread.CurrentThread.CurrentCulture.Name // it should return "en-GB"

Documentation


Note: It is hard to tell from your question exactly where the problem lies. As your question does not specify the exact case of where you are seeing this problem:

  • Server (eg: Controllers)
  • Model
  • View
  • Client

Assuming that you don't alter the culture at any point and do not have any forced formatting occuring anywhere, then the solution above should work fine.

Here are some alternative areas to look at:

1.) Overide the InitializeCulture method

protected override void InitializeCulture()
{
    var hidden = this.Request.Form["hidden"];
    var culture = this.Request.Form[hidden];
    if (!string.IsNullOrWhiteSpace(culture))
    {
        this.Culture = culture;
        this.UICulture = culture;
    }

    base.InitializeCulture();
}

2.) Set the culture in the assembly attributes

[assembly: AssemblyCulture("en-US")]
[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.MainAssembly)]

3.) Set the culture in page attributes

<%@ Page Culture="en-US" UICulture="en-US" Title="..." %>

// Razor Symtax
@{
    Page.Culture = "en-US"
    Page.UICulture = "en-US"
    Page.Title = "..."
}

4.) Your web.configs file.

<globalization uiCulture="en-US" culture="en-US" enableClientBasedCulture="false" />

Note that the enableClientBasedCulture is set to false

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download