以日期格式固定月份和日期的长度?

时间:2011-06-29 03:13:32

标签: java date format

有没有办法将Date对象格式化为Day和Month的固定长度,以便在列中保持良好的对齐? 例如:

15 May      2010
10 January  2010

而不是

15 May 2010
10 January 2010

谢谢!

1 个答案:

答案 0 :(得分:6)

查看java.util.Formatter类,其格式方法与String.format(...)相同,类似于System.out.printf。

例如:

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class FormatDateCalendar {
   public static final String FORMAT_STRING = "%1$-3td %1$-9tB %1$tY";
   public static void main(String[] args) {
      Calendar c1 = new GregorianCalendar(2011, Calendar.FEBRUARY, 3);
      Calendar c2 = new GregorianCalendar(2010, Calendar.MAY, 15);
      Date today = new Date();

      System.out.printf(FORMAT_STRING + "%n", c1);
      System.out.printf(FORMAT_STRING + "%n", c2);
      System.out.printf(FORMAT_STRING + "%n", today);
   }
}