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

Changing Date Format Symbols

The format method of the SimpleDateFormat class returns a String comprised of digits and symbols. For example, in the String "Friday, April 10, 1998," the symbols are "Friday" and "April." If the symbols encapsulated in SimpleDateFormat don't meet your needs, you can change them with the DateFormatSymbols(in the API reference documentation)class. You can change symbols that represent names for months, days of the week, and time zones, among others.

Let's take a look at an example that modifies the short names of the days of the week. You'll find the full source code for this example in the file named DateFormatSymbolsDemo.java. In this example, we begin by creating a DateFormatSymbol object for the U.S. Locale. We're curious about the default abbreviations that DateFormatSymbol encapsulates for the days of the week, so we invoke the getShortWeekdays method. We've decided to create uppercase versions of these abbreviations in the String array called capitalDays. Then we apply the new set of symbols in captitalDays to the DateFormatSymbol object with the setShortWeekdays method. Finally, we instantiate the SimpleDateFormat class, specifying the DateFormatSymbol that has the new names. Here is the source code:

Date today;
String result;
SimpleDateFormat formatter;
DateFormatSymbols symbols;
String[] defaultDays;
String[] modifiedDays;

symbols = new DateFormatSymbols(new Locale("en","US"));
defaultDays = symbols.getShortWeekdays();

for (int i = 0; i < defaultDays.length; i++) {
   System.out.print(defaultDays[i] + "  ");
}
System.out.println();

String[] capitalDays = {
   "", "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};
symbols.setShortWeekdays(capitalDays);

modifiedDays = symbols.getShortWeekdays();
for (int i = 0; i < modifiedDays.length; i++) {
   System.out.print(modifiedDays[i] + "  ");
}

System.out.println();
System.out.println();

formatter = new SimpleDateFormat("E", symbols);
today = new Date();
result = formatter.format(today);
System.out.println(result);
The output generated by the preceeding code is shown below. The first line contains the short names for the days of the week before we've changed them. The second line contains the upper case names we applied with the setShortWeekdays method. These first two lines appear to be indented, because the first String in the array of names is null. The last line shows the result returned by the SimpleDateFormat.format method.
  Sun  Mon  Tue  Wed  Thu  Fri  Sat  
  SUN  MON  TUE  WED  THU  FRI  SAT  

WED


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