Java Reference
In-Depth Information
The following snippet of code formats the current date and time in the default locale (US in this case). You will
get different output when you run the code. It uses a
ZonedDateTime
argument that holds the current date/time with
time zone.
ZonedDateTime currentTime = ZonedDateTime.now();
System.out.printf("%tA %<tB %<te, %<tY %n", currentTime);
System.out.printf("%TA %<TB %<te, %<tY %n", currentTime);
System.out.printf("%tD %n", currentTime);
System.out.printf("%tF %n", currentTime);
System.out.printf("%tc %n", currentTime);
System.out.printf("%Tc %n", currentTime);
Saturday January 25, 2014
SATURDAY JANUARY 25, 2014
01/25/14
2014-01-25
Sat Jan 25 00:47:26 CST 2014
SAT JAN 25 00:47:26 CST 2014
Note the effect of using the uppercase variant
'T'
as the conversion character. It formats the argument in
uppercase letters. The definition of uppercase depends on the locale that is used. If the locale does not have different
uppercase and lowercase letters, the output will be the same when you use
'T'
or
't'
as the conversion character.
Summary
In this chapter, you learned how to format dates and times using the
DateFormat
and
SimpleDateFormat
classes
in the
java.text
package. The
DateFormat
class formats dates and times using predefined formats whereas the
SimpleDateFormat
class lets you specify custom formats.
The
NumberFormat
class is used to format a number in a particular locale's predefined format. The
DecimalFormat
class is used to format a number in a format of your choice in a particular locale.
You can use
printf
-style formatting using the
java.util.Formatter
class to format strings, numbers, and
date/time. It lets you send the formatted output to a
StringBuilder
, a
StringBuffer
, a
File
, an
OutputStream
,
a
PrintStream
, etc. You have been using the
System.out.format()
and
System.out.printf
() methods to send the
formatted output to the standard output. Use the
static String.format()
method to get a formatted string.
Use a
Formatter
to send the formatted output to the destination of your choice. You can implement the
Formattable
interface to apply a custom formatting to the objects of the class.