开发者

Whats the difference in using a and aaa in SimpleDateFormat

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 th开发者_开发百科e same.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜