4

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!

Loc Phan
  • 4,304
  • 4
  • 29
  • 35

1 Answers1

6

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);
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thanks. That's correct what I asked, but I still have trouble with the letters' width, it make the alignment wrong with some fonts. – Loc Phan Jun 29 '11 at 05:04
  • 1
    @Loc - if you are trying to deal with alignment of variable width characters, you won't be able to do it with plain strings. You'll need to use some kind of markup; e.g. HTML fragments, or Swing layouts. – Stephen C Jun 29 '11 at 06:28
  • @Stephen: Yes, in need I want to make the date parts are vertically aligned. But I can't use HTML because it seem slow. I can use different labels to store different parts, but it seem too manually and hard to make the text wrapped if the column width is small. – Loc Phan Jun 29 '11 at 06:36
  • @Loc - well perhaps you should ask a new question, this time making it clear **precisely** what is supposed to be displaying the dates, and what you've tried. – Stephen C Jun 29 '11 at 07:32
  • Created: http://stackoverflow.com/questions/6517373/alignment-date-parts-in-jtable-column-formatted-in-propotional-font – Loc Phan Jun 29 '11 at 08:13