为不同的Locales定制java.text格式化程序

5 java locale localization internationalization

构建支持不同Locales的Java应用程序,但希望自定义DateFormat显示超出FULL,LONG,MEDIUM和SHORT DateFormat选项之间的可用范围.想要做一些事情,比如在DateFormat.getDateTimeFormat()的日期和时间组件之间放置一个字符,小写AM/PM等,至少为英语.

可以想到3种方法:

1)如果locale是english,请在新的SimpleDateFormat对象上使用我的自定义格式字符串.

2)修改现有语言环境的默认格式字符串

3)创建一个新的语言环境变体,指定我想要的格式字符串

无法弄清楚如何做2或3(或者如果它甚至可能),并且宁愿不做1 ...有没有人之前处理过这样的事情?

此外,似乎需要2或3来降低AM/PM?(为语言环境的dateformat设置指定AmPmMarkers资源)

Pau*_*lin 0

我处理过的唯一类似的事情是“strftime”和“locale”说意大利语应该在时间字段之间使用冒号,但Java在它们之间放置句号。所以我添加了以下代码:

  // 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);
      }
Run Code Online (Sandbox Code Playgroud)