Date and Time Formatting |
Theformat
method of theSimpleDateFormat
class returns aString
comprised of digits and symbols. For example, in theString
"Friday, April 10, 1998," the symbols are "Friday" and "April." If the symbols encapsulated inSimpleDateFormat
don't meet your needs, you can change them with the DateFormatSymbolsclass. 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 thatDateFormatSymbol
encapsulates for the days of the week, so we invoke thegetShortWeekdays
method. We've decided to create uppercase versions of these abbreviations in theString
array calledcapitalDays
. Then we apply the new set of symbols incaptitalDays
to theDateFormatSymbol
object with thesetShortWeekdays
method. Finally, we instantiate theSimpleDateFormat
class, specifying theDateFormatSymbol
that has the new names. Here is the source code: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 theDate 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);setShortWeekdays
method. These first two lines appear to be indented, because the firstString
in the array of names is null. The last line shows the result returned by theSimpleDateFormat.format
method.Sun Mon Tue Wed Thu Fri Sat SUN MON TUE WED THU FRI SAT WED
Date and Time Formatting |