Whats the difference in using a and aaa in SimpleDateFormat

时光毁灭记忆、已成空白 提交于 2019-12-06 15:42:40

Can't do! If the pattern is 4 letters or less, short format is used. So 'a', 'aa', 'aaa' and 'aaaa' are identical.

All you can do is to format it without 'a', and add 'A' or 'P' manually.

Having said that, using 'HH' (24-hours clock) why would you need AM/PM?

I believe for am/pm markers, there's no difference between "short" and "long".

In particular, DateFormatSymbols.getAmPmStrings() returns just two strings - and there's no getShortAmPmStrings() call or anything like that.

Quoting from the Javadoc of SimpleDateFormat:

For formatting, if the number of pattern letters is 4 or more, the full form is used; otherwise a short or abbreviated form is used if available

Thus: (a) If you expect to see a difference use aaaa (4 x a) rather than aaa (4 x a). (b) Given that AM/PM has no short form (or long form) then for the a specifier the number of repetition does not matter.

And just to be a bit more thorough, I ran the following program. It found zero cases where the formatting was affected.

Date date = new Date();
int n = 0;
for (String country : Locale.getISOCountries()) {
  for (String language : Locale.getISOLanguages()) {
    Locale loc = new Locale(language, country);
    String as = "";
    String prev = null;
    for (int i = 0; i < 20; ++i) {
      ++n;
      as += "a";
      String current = new SimpleDateFormat(as, loc).format(date);
      if (prev != null && !prev.equals(current)) {
        System.out.println("Locale: " + loc + ", as=" + as + ", current="
          + prev + ", next=" + current);
      }

      prev = current;
    }
  }
}
System.out.println("Tried out " + n + " combinations.");    

There is no difference, what were you expecting to differ?

Based on this site (http://javatechniques.com/blog/dateformat-and-simpledateformat-examples/):

“a” -> “AM”

“aa” -> “AM”

Then the option you have is

time = time.substring(0,time.length()-1);

:) Silly but will work

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