javadateformat

Fixed length of month and day in date format, to align columns of text?


Is there any way to format Date object to made fixed length of Day and Month in order to have good alignment in a column? For example:

15 May      2010
10 January  2010

Instead of

15 May 2010
10 January 2010

Thanks!


Solution

  • Have a look at the java.util.Formatter class whose format method is the same as String.format(...) and similar to System.out.printf.

    For example:

    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);
       }
    }