0

I want to display dates and currency amounts in my users chosen format.
How can I retrive this from the client machine?

Alternatively, is there some other way to format dates/currency correctly?

Thanks

SeanX
  • 1,851
  • 20
  • 28

2 Answers2

1

A browser exposes it's locale: You can retrieve it by using ** Thread.CurrentThread.CurrentUICulture**

read more about this here and here

You can overwrite their Culture with a culture of your chosing (if the select another language from a menu perhaps)

to format the date time, and string read here

Watch out, setting a culture happens very soon in a page cycle, if you set it to late, the resource files will be those of a previous selected Culture.

To set the Culture early in the cycle you can create a basepage (that inherits ViewPage){}

using System.Globalization;
using System.Threading;
using System.Web.Mvc;

namespace NerdDinner.Views
{
    public class NerdDinnerViewPage<T> : ViewPage<T> where T : class
    {
        protected override void InitializeCulture()
        {
            base.InitializeCulture();

            Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentCulture.Clone() as CultureInfo;

            if (Thread.CurrentThread.CurrentCulture != null)
            {
                Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator = ".";
                Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";
            }
        }
    }
}

page

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="NerdDinner.Views.NerdDinnerViewPage<NerdDinner.Models.DinnerFormViewModel>" %>

here is the full example, but I copied the code for easyness: example

another approach is using the global asax which can be found here

Community
  • 1
  • 1
Nealv
  • 6,856
  • 8
  • 58
  • 89
  • Thread.CurrentThread.CurrentUICulture requires UICulture="auto" Culture="auto" in the view's page declaration. eg <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" UICulture="auto" Culture="auto" %> – SeanX Jul 27 '10 at 23:05
0

In order to select a useful default for the .NET tools at your disposal (such as CultureInfo), my recommendation (in a web scenario) would be to parse the HTTP user agent string, as in the examples provided here. But in addition, the user should be able to override the default, and you ought to save the user's choice in a cookie and, if applicable, user options.

chryss
  • 7,459
  • 37
  • 46
  • in mvc you can get the current culture as described in my answer. This is the same as you said, but already parsed for you – Nealv Jul 27 '10 at 21:53
  • OK, I can see that. .NET MVC magic :). It might still help to remember where the data comes from. – chryss Jul 27 '10 at 22:16
  • absolutely very true, understanding what happens and how is 90% of all the magic that is IT :) – Nealv Jul 27 '10 at 23:57