Customizing java.text formatters for different Locales

可紊 提交于 2019-12-05 10:48:30

Why not use a MessageFormat instead?

Use the pattern "{0,date,short} your text here {0,time,short}" to do what you want.

Java has a Class just for this, it is the ResourceBundle Class. Back it with a properties file and you have all that you need plus more.

Even without the ResourceBundle Class you could use properties files to hold all the SimpleDateFormat formats.

Settings formats = new Settings();
Properties SDFFormats = formats.load(propertiesFile);

String SDFAmerica = SDFFormats.getProperty("FormatAmerica");

While the entry into the properties file might read

FormatAmerica = MMM-dd-yyyy

The only thing similar I've dealt with is the fact that "strftime" and "locale" say that Italian should use colons between the time fields, but Java puts full-stops between them. So I've added the following code:

  // This is an incredibly ugly hack, but it's based on the fact that
  // Java for some reason decided that Italy uses "." between
  // hours.minutes.seconds, even though "locale" and strftime say
  // something different.
      hmsTimeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM);
      if (hmsTimeFormat instanceof SimpleDateFormat)
      {
        String str = ((SimpleDateFormat)hmsTimeFormat).toPattern();
        str = str.replace('.', ':');
        hmsTimeFormat = new SimpleDateFormat(str);
      }

Most satisfying way to solve this that we've figured out is to load Strings am,pm,formatString from a locale-specific resource bundle, and then:

SimpleDateFormat sdf = (SimpleDateFormat)sdf.getDateTimeInstance(DateTime.SHORT,DateTime.SHORT, locale);
if (formatString != null) {
    sdf = new SimpleDateFormat(formatString);
}
if (am!= null && pm != null) {
    DateFormatSymbols symbols = sdf.getDateFormatSymbols();
    symbols.setAmPmStrings(new String[]{am, pm});
    sdf.setDateFormatSymbols(symbols);
}

Paul: not sure there's a separator in the DateFormatSymbols, though... so you probably need to keep the str.replace

I recommend using Joda Time for your date formatting. It is has powerful yet elegant flexibility in its formatting. You'll probably find that its formatters make what you want to do extremely simple.

BTW: once you go Joda you'll never go back!

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