|
|
Date and Time Formatting |
Theformatmethod of theSimpleDateFormatclass returns aStringcomprised of digits and symbols. For example, in theString"Friday, April 10, 1998," the symbols are "Friday" and "April." If the symbols encapsulated inSimpleDateFormatdon'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
DateFormatSymbolobject for the U.S.Locale. We're curious about the default abbreviations thatDateFormatSymbolencapsulates for the days of the week, so we invoke thegetShortWeekdaysmethod. We've decided to create uppercase versions of these abbreviations in theStringarray calledcapitalDays. Then we apply the new set of symbols incaptitalDaysto theDateFormatSymbolobject with thesetShortWeekdaysmethod. Finally, we instantiate theSimpleDateFormatclass, specifying theDateFormatSymbolthat 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);setShortWeekdaysmethod. These first two lines appear to be indented, because the firstStringin the array of names is null. The last line shows the result returned by theSimpleDateFormat.formatmethod.Sun Mon Tue Wed Thu Fri Sat SUN MON TUE WED THU FRI SAT WED
|
|
Date and Time Formatting |