Java Reference
In-Depth Information
Let's try a similar format with the same date but a different locale. The following state-
ments use a DateFormat object for the country Germany:
DateFormat de = DateFormat.getDateTimeInstance(
DateFormat.MEDIUM,
DateFormat.FULL,
Locale.GERMANY);
System.out.println(de.format(d));
The output of the statements looks something like this:
31.01.1984 17.47 Uhr MST
Between the various date styles, time styles, and locales, you have a lot of options for
formatting dates and times using the DateFormat class. The class is also used for parsing
dates, as the next section shows.
The DateFormat.parse Method
The DateFormat class contains the following parse method for parsing strings into dates:
public Date parse(String source) throws ParseException .
The return value is of type java.util.Date , and the ParseException is thrown when
the beginning of the string cannot be parsed into a date successfully.
The format of the String object depends on both the style and the locale of the Date-
Format object. The following statements parse a date string in the SHORT style of the U.S.
locale, and then format the resulting Date object in the FULL style of the France locale:
7. DateFormat shortFormat = DateFormat.getDateInstance(
8. DateFormat.SHORT,
9. Locale.US);
10. String s = “01/31/1984”;
11. try {
12. Date date = shortFormat.parse(s);
13. DateFormat fullFormat = DateFormat.getDateInstance(
14. DateFormat.FULL,
15. Locale.FRANCE);
16. System.out.println(fullFormat.format(date));
17. }catch(ParseException e) {
18. e.printStackTrace();
19. }
The shortFormat object has the SHORT date style and U.S. locale, and on line 12 it parses
the string ”01/31/1984” . The resulting Date object is printed on line 16 using a FULL style
with the France locale. The output is
mardi 31 janvier 1984
Search WWH ::




Custom Search