@ Nonnull public static Locale getLocaleFromString ( @ Nullable final String sLocaleAsString ) { if ( StringHelper . hasNoText ( sLocaleAsString ) ) { // not specified => getDefault return SystemHelper . getSystemLocale ( ) ; } String sLanguage ; String sCountry ; String sVariant ; int i1 = sLocaleAsString . indexOf ( LOCALE_SEPARATOR ) ; if ( i1 < 0 ) { // No separator present -> use as is sLanguage = sLocaleAsString ; sCountry = "" ; sVariant = "" ; } else { // Language found sLanguage = sLocaleAsString . substring ( 0 , i1 ) ; ++ i1 ; // Find next separator final int i2 = sLocaleAsString . indexOf ( LOCALE_SEPARATOR , i1 ) ; if ( i2 < 0 ) { // No other separator -> country is the rest sCountry = sLocaleAsString . substring ( i1 ) ; sVariant = "" ; } else { // We have country and variant sCountry = sLocaleAsString . substring ( i1 , i2 ) ; sVariant = sLocaleAsString . substring ( i2 + 1 ) ; } } // Unify elements if ( sLanguage . length ( ) == 2 ) sLanguage = sLanguage . toLowerCase ( Locale . US ) ; else sLanguage = "" ; if ( sCountry . length ( ) == 2 ) sCountry = sCountry . toUpperCase ( Locale . US ) ; else sCountry = "" ; if ( sVariant . length ( ) > 0 && ( sLanguage . length ( ) == 2 || sCountry . length ( ) == 2 ) ) sVariant = sVariant . toUpperCase ( Locale . US ) ; else sVariant = "" ; // And now resolve using the locale cache return LocaleCache . getInstance ( ) . getLocale ( sLanguage , sCountry , sVariant ) ; }
Convert a String in the form language - country - variant to a Locale object . Language needs to have exactly 2 characters . Country is optional but if present needs to have exactly 2 characters . Variant is optional .