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 theDateFormatclass is a two-step process. First, you create a formatter with thegetDateInstancemethod. Second, you invoke theformatmethod, which returns aStringcontaining 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. SinceDateFormatis 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
DEFAULTformatting style. TheDEFAULTstyle is just one of the predefined formatting styles that theDateFormatclass 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 DEFAULTJun 30, 2009 30 juin 2009 SHORT6/30/09 30/06/09 MEDIUMJun 30, 2009 30 juin 2009 LONGJune 30, 2009 30 juin 2009 FULLTuesday, June 30, 2009 mardi 30 juin 2009
Dateobjects represent both dates and times. Formatting times with theDateFormatclass is similar to formatting dates, except that you create the formatter with thegetTimeInstancemethod, 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 DEFAULT7:03:47 AM 7:03:47 SHORT7:03 AM 07:03 MEDIUM7:03:47 AM 07:03:07 LONG7:03:47 AM PDT 07:03:45 PDT FULL7:03:47 AM PDT 7.03 Uhr PDT
To display a date and time in the sameString, create the formatter with thegetDateTimeInstancemethod. 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 DEFAULTJun 30, 2009 7:03:47 AM 30 juin 2009 07:03:47 SHORT6/30/09 7:03 AM 30/06/09 07:03 MEDIUMJun 30, 2009 7:03:47 AM 30 juin 2009 07:03:47 LONGJune 30, 2009 7:03:47 AM PDT 30 juin 2009 07:03:47 PDT FULLTuesday, June 30, 2009 7:03:47 AM PDT mardi 30 juin 2009 07 h 03 PDT