Back to the main page

String Formatting
printf(String format, Object... o)
String.format(String format, Object... o)
e.g.
Calendar c = Calendar.getInstance();
String s = String.format("Time: %1$tH:%1$tM", c)


Format specifiers for general, character and numeric types

%[argumentIndex$][flags][width][.precision]conversion
flags
-(hyphen)left justified
+always include sign
(space) include leading space
0zero padded
,include locale specific grouping separators
(enclose negative numbers in parentheses
widthminimum number of characters


Format specifiers for dates and times

%[argumentIndex$][flags][width]conversion
conversion:this is always two characters beginning with t or T


Format specifiers which don't correspond to arguments

%[argumentIndex$][flags]conversion
e.g. %n platform specific new line


General conversions
flags
b or BBoolean e.g. true or TRUE
h or HHashcode, null or Integer.toHexString(arg.hashCode())
s or SNull or if arg implements Formattable arg.formatTo() else arg.toString()
c or CUnicode character
dDecimal
oOctal
x or XHexidecimal
e or EScientific
fFloating point
g or GDecimal or scientific depending on precision and value after rounding
a or AHexidecimal floating with significand and exponent


Date conversions (precede with t or T
flags
BFull month name
h or b3 character month name
ALocale specific full weekday name
aLocale specific short weekday name
CCentury
Y4 digit year
y2 digit year
jDay of year
m2 digit month number
d2 digit day of month number
e1 or 2 digit day of month number


Time conversions (precede with t or T)
flags
HHour 24hr
IHour 12hr (2 digits)
kHour 12hr (1 or 2 digits)
MMinute (2 digits)
SSecond (2 digits)
LMillisecond (3 digits)
NNanosecond (9 digits)
p or Pam/pm or AM/PM
zGMT offset
ZTimezone
sSeconds since 1/1/1970
QMilliseconds since 1/1/1970


Date & Time shortcuts (for uppercase precede with T not t)
flags
tR%tH:%tM
tT%tH:%tM:%tS
tr%tI:%tM:%tS %tP
tD%tm/%td/%tY
tF%tY-%tm-%td
tc%ta %tb %td %tT %tZ %tY