What is the difference between creating locale for en-US and en_US?

被刻印的时光 ゝ 提交于 2019-12-08 23:04:53

问题


I am having all my resourcebundle values in table and formatted as per requirement.i have to change the languages in the website based on User selection in drop down in top of the page. If i use language code as en_US then its working fine. if i Use en-Us as Language Code then its not working. What might be the problem. Which is correct to follow?


回答1:


"en" is the language code specified by ISO 639. while US is country code specified by 3166.
In Java, the Locale object recognizes the language as languageCode_countryCode (e.g. en_US) and not as languageCode-countryCode.




回答2:


"en-US" is an IETF language tag. While Java'a Locale class was clearly based on IETF language tags, it uses underscores in place of hyphens when separating language codes from country codes (and also variants), so calling toString() on the equivalent Locale will give you en_US.

As of Java 7 you can use Locale.forLanguageTag(String) and toLanguageTag() to convert between language tags and Locale objects.

When converting strings to Locale objects it's a good idea to normalize by splitting components on hyphens and underscores, lowercasing the first component (the language code) and upper-casing the second component (the country code).




回答3:


Or you could use Locale us = Locale.forLanguageTag("en-US") and us.toLanguageTag(), and that will do the conversion for you without having to create your own error-prone implementation.




回答4:


As of Java8, Initializing the locale should be done using the language tag "en-US" Locale.forLanguageTag("en-US").toString(); returns the output: en_US

Where as Locale.forLanguageTag("en_US") does not create the required locale. It will default to the system locale. Locale.forLanguageTag("en_US").toString() returns null



来源:https://stackoverflow.com/questions/4632885/what-is-the-difference-between-creating-locale-for-en-us-and-en-us

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!