Java Reference
In-Depth Information
Chapter 13
Formatting Data
Java provides a rich set of APIs for formatting data. The data may include simple values such as a numbers or objects
such as strings, dates, and other types of objects. In this chapter, you will learn
•
How to format and parse dates and numbers
printf
-style formatting
•
How to use the
•
How to create a class that uses a custom formatter
Formatting Dates
Java 8 provides a Date-Time API to work with dates and times, and to format and parse them. The Date-Time API was
discussed in Chapter 12. If you are writing new code that is related to dates and times, you are advised to use the new
Date-Time API. This section is provided in case you need to work with legacy code that uses old ways of formatting
dates and time that existed before Java 8.
In this section, I will discuss how to format dates. I will also discuss how to parse a string to create a date object.
You can format dates in predefined formats or formats of your choice. The Java library provides two classes to
format dates:
java.text.DateFormat
•
java.text.SimpleDateFormat
Use the
DateFormat
class to format dates using a predefined format. It is an
abstract
class. The class is abstract,
so you cannot create an instance of this class using the
new
operator. You can call one of its
getXxxInstance()
methods,
where
Xxx
can be
Date
,
DateTime
, or
Time
, to get the formatter object, or just
getInstance()
. The formatted text
depends on two things: style and locale. Use the
format()
method of the
DateFormat
class to format a date and time.
The style of formatting determines how much datetime information is included in the formatted text, whereas the
locale determines how all pieces of information are assembled. The
DateFormat
class defines five styles as constants:
•
DateFormat.DEFAULT
•
DateFormat.SHORT
•
DateFormat.MEDIUM
•
DateFormat.LONG
•
DateFormat.FULL
The
DEFAULT
format is the same as
MEDIUM
, unless you use
getInstance()
where the default is
SHORT
. Table
13-1
shows the same date formatted in different styles for a US locale.
•