24.5.1. Using Formatter with Dates and Times
The java.util.Formatter class, described in Chapter 22, also supports the formatting of date and time
information using a supplied Date or Calendar object, or a date represented as a long (or Long). Using
the available format conversions you can extract information about that date/time, including things like the
day of the month, the day of the week, the year, the hour of the day, and so forth.
The output of the formatter is localized according to the locale associated with that formatter, so things like
the name of the day and month will be in the correct languagehowever, digits themselves are not localized.
Unlike DateFormat, a formatter cannot help you with localization issues such as knowing whether the
month or the day should come first in a dateit simply provides access to each individual component and your
program must combine them in the right way.
A date/time conversion is indicated by a format conversion of t (or T for uppercase output), followed by
various suffixes that indicate what is to be output and in what form. The following table lists the conversion
suffixes related to times:
H Hour of the day for 24-hour clock format. Two digits: 0023
I Hour of the day for 12-hour clock format. Two digits: 0112
k Hour of the day for 24-hour clock format: 023
l Hour of the day for 12-hour clock format: 112
M Minute within the hour. Two digits: 0059
S Seconds within the minute. Two digits: 0060 (60 is a leap second)
L Milliseconds within the second. Three digits: 000999
N Nanoseconds within the second. Nine digits: 000000000999999999
p Locale specific AM or PM marker.
z Numeric offset from GMT (as per RFC 822). E.g. +1000
Z String representing the abbreviation for the time zone
s Seconds since the epoch.
Q Milliseconds since the epoch.
So, for example, the following code will print out the current time in the familiar hh:mm:ss format:
System.out.printf("%1$tH:%1$tM:%1$tS %n", new Date());
The conversion suffixes that deal with dates are
B Full month name
b Abbreviated month name
h Same as 'b'
A Full name of the day of the week