简体   繁体   中英

How can I get the client side date and currency formats?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM