8.2 The Date class |
Before the JDK 1.1 release the Date class provide several functions for the manipulation of dates and the formatting and parsing of date strings. However these functions where not adaptable for internationalization. To this end two new classes have been added to the Java API, the Calendar class and the DateFormat class.
The Calendar class should be used to convert between date and time fields. The DateFormat class should be used to format and parse date strings.
To retrieve a DateFormat object configured for the current locale you can use the following code:
DateFormat formatter = DateFormat.getDateInstance();To retrieve a DateFormat object configured for a particular local you can use the following code:
DateFormat formatter = DateFormat.getDateInstance(Locale.FRANCE);The format() method on the DateFormat class will format a Date object into a String based on the configuration of the DateFormat Object. The Following code displays the date formatted for the current locale and the displays the same date formatted for France.
Date aDate = new Date(); // creates a date object initialized to the current date and time DateFormat localFormatter = DateFormat.getDateInstance(DateFormat.FULL); DateFormat franceFormatter = DateFormat.getDateInstance(DateFormat.FULL,Locale.FRANCE); System.out.println("Date looks like this locally : " + localFormatter.format( aDate ) ); System.out.println("Date looks like this in France: " + franceFormatter.format( aDate ) );The parse() method on the DateFormat class will convert a String to a Date.
If you want exact control of the date formatting you can use the SimpleDateFormat
class which allows you to specify masks for the formatting and parsing
of date strings.