CultureInfo in JavaScript

In C #, I use the method below to get CultureInfo.

System.Globalization.CultureInfo.CurrentCulture.Name // output :en-US 

Can someone tell me how can I get CultureInfo in JavaScript?

+8
javascript
source share
2 answers

A very simple way is to display it as, for example:

 <script> var cultureInfo = '@System.Globalization.CultureInfo.CurrentCulture.Name'; </script> 

This is razor syntax if you are using classic asp.net and then use:

 <script> var cultureInfo = '<%= System.Globalization.CultureInfo.CurrentCulture.Name %>'; </script> 
+9
source share

It depends on your purpose. If you want the whole site to be considered the same culture as your server, you can only use System.Globalization.CultureInfo.CurrentCulture.Name and remove the shortened if-then line in the first code snippet. This is not recommended if you have a global website.

Include the following at the bottom of the page:

  <input id="currentCulture" type="hidden" value="<%=((Request.UserLanguages != null && Request.UserLanguages.Length > 0) ? new System.Globalization.CultureInfo(Request.UserLanguages.First(), true).Name : System.Globalization.CultureInfo.CurrentCulture.Name) %>" /> 

Now you can get user-specific culture information in your javascript using:

 $("#currentCulture").val(); //Jquery document.getElementById("currentCulture").value; //Pure javascript 

Inside your code, any required datetime parsing, pass the culture information provider to the parse and tryparse and Convert.ToDateTime functions using the following:

  CultureInfo info = ((Request.UserLanguages != null && Request.UserLanguages.Length > 0) ? new CultureInfo(Request.UserLanguages.First(), true) : System.Globalization.CultureInfo.CurrentCulture); 

Note. If you use the JQuery UI and have cultures that are not enabled by default (e.g. en-CA or en-GB), you will have to add them. You can get the code here:

https://code.google.com/p/dobo/source/browse/trunk/dobo/Kooboo.CMS/Kooboo.CMS.Web/Scripts/jquery-ui-i18n/?r=7

You can then turn it on dynamically by following the example below:

  $.datepicker.regional['en-CA'] = { "Name": "en-CA", "closeText": "Close", "prevText": "Prev", "nextText": "Next", "currentText": "Today", "monthNames": ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ""], "monthNamesShort": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ""], "dayNames": ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], "dayNamesShort": ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], "dayNamesMin": ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], "dateFormat": "dd/mm/yy", "firstDay": 0, "isRTL": false }; $(".datepick").datepicker($.datepicker.setDefaults($.datepicker.regional[$("#currentCulture").val()])); 
0
source share

All Articles