THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1
a Short name of the day of the week

C The four digit year divided by 100. Two digits: 0099

Y Year. Four digits: 00009999

y Year: Two digits: 0099

j Day of the year. Three digits: 001999

m Month in year. Two digits: 0199

d Day of month. Two digits: 0199

e Day of month: 199

Naturally, the valid range for day of month, month of year, and so forth, depends on the calendar that is being
used. To continue the example, the following code will print the current date in the common mm/dd/yy
format:


System.out.printf("%1$tm/%1$td/%1$ty %n", new Date());


As you can see, all the information about a date or time can be extracted and you can combine the pieces in
whatever way you need. Doing so, however, is rather tedious both for the writer and any subsequent readers
of the code. To ease the tedium a third set of conversion suffixes provides convenient shorthands for common
combinations of the other conversions:


R Time in 24-hour clock hh:mm format ("%tH:%tM")

T Time in 24-hour clock hh:mm:ss format ("%tH:%tM:%tS")

r Time in 12-hour clock h:mm:ss am/pm format ("%tI:%tM:%tS %Tp")

D Date in mm/dd/yy format ("%tm/%td/%ty")

F Complete date in ISO 8601 format ("%tY-%tm-%TD")

c Long date and time format ("%ta %tb %td %tT %tZ %tY")

So the previous examples could be combined in the more compact and somewhat more readable


System.out.printf("%1$tT %1$tD %n", new Date());


As with all format conversions a width can be specified before the conversion indicator, to specify the
minimum number of characters to output. If the converted value is smaller than the width then the output is
padded with spaces. The only format flag that can be specified with the date/time conversions is the '' flag for
left-justificationif this flag is given then a width must be supplied as well.

Free download pdf