Whats the difference in using a and aaa in SimpleDateFormat

寵の児 提交于 2019-12-10 11:32:42

问题


I want to display current date as 00:50:32 A

Here is my code

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss a");
String time = sdf.format(date);
System.out.println("time : " + time);

But it print as:

time : 00:50:32 AM

I tried both HH:mm:ss a and HH:mm:ss aaa, but results are the same.


回答1:


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?




回答2:


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.




回答3:


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.");    



回答4:


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”




回答5:


Then the option you have is

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

:) Silly but will work



来源:https://stackoverflow.com/questions/5893297/whats-the-difference-in-using-a-and-aaa-in-simpledateformat

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