Previous | Next | Trail Map | Internationalization | Date and Time Formatting

Formatting with Patterns

In the previous section, Using Predefined Formats, we described the formatting styles provided by the DateFormat class. In most cases, these predefined formats are adequate. However, if you want to create your own customized formats, you'll want to use the SimpleDateFormat(in the API reference documentation)class.

In the text that follows, we'll provide several code examples that demonstrate the methods of the SimpleDateFormat class. You can find the full source code for the examples in the file named SimpleDateFormatDemo.java.

About Patterns

When you create a SimpleDateFormat object, you specify a pattern String. The contents of the pattern String determines the format of the date and time. For a full description of the pattern's syntax, see the tables in the section Date Format Pattern Syntax. We'll show you some sample patterns in the example that follows.

In the following lines of code, we specify the pattern String when creating the SimpleDateFormat object, and then invoke the format method. The String returned by the format method contains the formatted date and time, and is ready to be displayed.

Date today;
String output;
SimpleDateFormat formatter;

formatter = new SimpleDateFormat(pattern, currentLocale);
today = new Date();
output = formatter.format(today);

System.out.println(pattern + "   " + output);
The following table shows the output generated by the preceeding code example when the U.S. Locale is specified:

pattern output
dd.MM.yy 09.04.98
yyyy.MM.dd G 'at' hh:mm:ss z 1998.04.09 AD at 06:15:55 PDT
EEE, MMM d, ''yy Thu, Apr 9, '98
h:mm a 6:15 PM
H:mm 18:15
H:mm:ss:SSS 18:15:55:624
K:mm a,z 6:15 PM,PDT
yyyy.MMMMM.dd GGG hh:mm aaa 1998.April.09 AD 06:15 PM

Patterns and Locale

The SimpleDateFormat class is locale-sensitive. If you instantiate SimpleDateFormat without a Locale parameter, it will format the date and time according to the default Locale. Both the pattern and the Locale determine the format. For the same pattern, SimpleDateFormat may format a date and time differently if the Locale varies.

In the example code that follows, the pattern is hardcoded in the statement that creates the SimpleDateFormat object:

Date today;
String result;
SimpleDateFormat formatter;

formatter = new SimpleDateFormat("EEE d MMM yy", currentLocale);
today = new Date();
result = formatter.format(today);

System.out.println("Locale: " + currentLocale.toString());
System.out.println("Result: " + result);
The preceeding code example generates the output that follows. Although the pattern is hardcoded, the resulting date format changes each time we specify a different Locale.
Locale: fr_FR
Result: ven 10 avr 98

Locale: de_DE
Result: Fr 10 Apr 98

Locale: en_US
Result: Thu 9 Apr 98


Previous | Next | Trail Map | Internationalization | Date and Time Formatting