DateFormat
class allows you to format dates and times with predefined styles in a
locale-sensitive manner. The sections that follow demonstrate how to
use the DateFormat
class with a program called
DateFormatDemo.java
.
Formatting dates with theDateFormat
class is a two-step process. First, you create a formatter with thegetDateInstance
method. Second, you invoke theformat
method, which returns aString
containing the formatted date. The following example formats today's date by calling these two methods:Date today; String dateOut; DateFormat dateFormatter; dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, currentLocale); today = new Date(); dateOut = dateFormatter.format(today); System.out.println(dateOut + " " + currentLocale.toString());The output generated by this code follows. Notice that the formats of the dates vary with
Locale
. SinceDateFormat
is locale-sensitive, it takes care of the formatting details for eachLocale
.30 juin 2009 fr_FR 30.06.2009 de_DE Jun 30, 2009 en_USThe preceding code example specified the
DEFAULT
formatting style. TheDEFAULT
style is just one of the predefined formatting styles that theDateFormat
class provides, as follows:
- DEFAULT
- SHORT
- MEDIUM
- LONG
- FULL
The following table shows how dates are formatted for each style with the U.S. and French locales:
Sample Date Formats
Style U.S. Locale French Locale DEFAULT
Jun 30, 2009 30 juin 2009 SHORT
6/30/09 30/06/09 MEDIUM
Jun 30, 2009 30 juin 2009 LONG
June 30, 2009 30 juin 2009 FULL
Tuesday, June 30, 2009 mardi 30 juin 2009
Date
objects represent both dates and times. Formatting times with theDateFormat
class is similar to formatting dates, except that you create the formatter with thegetTimeInstance
method, as follows:DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, currentLocale);The table that follows shows the various predefined format styles for the U.S. and German locales:
Sample Time Formats
Style U.S. Locale German Locale DEFAULT
7:03:47 AM 7:03:47 SHORT
7:03 AM 07:03 MEDIUM
7:03:47 AM 07:03:07 LONG
7:03:47 AM PDT 07:03:45 PDT FULL
7:03:47 AM PDT 7.03 Uhr PDT
To display a date and time in the sameString
, create the formatter with thegetDateTimeInstance
method. The first parameter is the date style, and the second is the time style. The third parameter is theLocale
. Here's a quick example:DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, currentLocale);The following table shows the date and time formatting styles for the U.S. and French locales:
Sample Date and Time Formats
Style U.S. Locale French Locale DEFAULT
Jun 30, 2009 7:03:47 AM 30 juin 2009 07:03:47 SHORT
6/30/09 7:03 AM 30/06/09 07:03 MEDIUM
Jun 30, 2009 7:03:47 AM 30 juin 2009 07:03:47 LONG
June 30, 2009 7:03:47 AM PDT 30 juin 2009 07:03:47 PDT FULL
Tuesday, June 30, 2009 7:03:47 AM PDT mardi 30 juin 2009 07 h 03 PDT