Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

842 Part II: The Java Library


System.out.println("Canada: " + df.format(date));
}
}

Sample output from this program is shown here:

Japan: 20:25
United Kingdom: 20:25:14 CDT
Canada: 8:25:14 o’clock PM CDT

TheDateFormatclass also has agetDateTimeInstance( )method that can format both
date and time information. You may wish to experiment with it on your own.

SimpleDateFormat Class

SimpleDateFormatis a concrete subclass ofDateFormat. It allows you to define your own
formatting patterns that are used to display date and time information.
One of its constructors is shown here:

SimpleDateFormat(StringformatString)

The argumentformatStringdescribes how date and time information is displayed. An example
of its use is given here:

SimpleDateFormat sdf = SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");

The symbols used in the formatting string determine the information that is displayed.
Table 27-6 lists these symbols and gives a description of each.
In most cases, the number of times a symbol is repeated determines how that data is
presented. Text information is displayed in an abbreviated form if the pattern letter is repeated
less than four times. Otherwise, the unabbreviated form is used. For example, a zzzz pattern
can display Pacific Daylight Time, and a zzz pattern can display PDT.
For numbers, the number of times a pattern letter is repeated determines how many digits
are presented. For example, hh:mm:ss can present 01:51:15, but h:m:s displays the same time
value as 1:51:15.
Finally, M or MM causes the month to be displayed as one or two digits. However, three
or more repetitions of M cause the month to be displayed as a text string.
The following program shows how this class is used:

// Demonstrate SimpleDateFormat.
import java.text.*;
import java.util.*;

public class SimpleDateFormatDemo {
public static void main(String args[]) {
Date date = new Date();
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("hh:mm:ss");
System.out.println(sdf.format(date));
sdf = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");
System.out.println(sdf.format(date));
sdf = new SimpleDateFormat("E MMM dd yyyy");
Free download pdf