Java Locale create from language tag

Description

Java Locale create from language tag

import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Locale;
public class Main {

   public static void main(String[] args) {
      String[] bcp47LangTags= {"fr-FR", "ja-JP", "en-US"};        
      Locale l = null;/*from   w  ww.  j  a va  2  s.  co m*/
      for (String langTag: bcp47LangTags) {
          l = Locale.forLanguageTag(langTag);
          displayLocalizedData(l);        
      }
   }

   private static void displayLocalizedData(Locale l) {
      long number = 123456789L;
      Date date = new Date();

      NumberFormat nf = NumberFormat.getInstance(l);
      DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, l);
      System.out.printf("Locale: %s\nNumber: %s\nDate: %s\n\n", l.getDisplayName(), nf.format(number), df.format(date));
   }
}
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

public class Main {
   public static void main(String[] args) {
      // Set ALL locales to fr-FR
      Locale.setDefault(Locale.FRANCE);
      demoDefaultLocaleSettings();/*from   w  ww . j  a  v a 2  s.  c  om*/

      // System default is still fr-FR
      // DISPLAY default is es-MX
      // FORMAT default is en-US
      Locale.setDefault(Locale.Category.DISPLAY, Locale.forLanguageTag("es-MX"));
      Locale.setDefault(Locale.Category.FORMAT, Locale.US);
      demoDefaultLocaleSettings();

      // System default is still fr-FR
      // DISPLAY default is en-US
      // FORMAT default is es-MX
      Locale.setDefault(Locale.Category.DISPLAY, Locale.US);
      Locale.setDefault(Locale.Category.FORMAT, Locale.forLanguageTag("es-MX"));
      demoDefaultLocaleSettings();

      // System default is Locale.US
      // Resets both DISPLAY and FORMAT locales to en-US as well.
      Locale.setDefault(Locale.US);
      demoDefaultLocaleSettings();

   }

   public static void demoDefaultLocaleSettings() {
      Date NOW = new Date();
      DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
      String date = df.format(NOW);
      System.out.printf("DEFAULT LOCALE: %s\n", Locale.getDefault());
      System.out.printf("DISPLAY LOCALE: %s\n", Locale.getDefault(Locale.Category.DISPLAY));
      System.out.printf("FORMAT LOCALE:  %s\n", Locale.getDefault(Locale.Category.FORMAT));
      System.out.printf(date);
   }
}



PreviousNext

Related