to move between a String object and a Date object representation of a date. The difference is that whilst the DateFormat uses the standard date formatting of the current locale, the SimpleDateFormat uses a custom format defined by special formatting characters commonly used in other languages.
SimpleDateFormat df1 = new SimpleDateFormat( "dd/MM/yy" ); SimpleDateFormat df2 = new SimpleDateFormat( "dd-MMM-yyyy" );
The full documentation of the SimpleDateFormat characters is in the J2SE API document, package java.text, class SimpleDateFormat.
Points to note:
1. The parse() method does not (by default) throw an Exception if the date is correctly formatted but invalid on the calendar (e.g. 29/2/2001), instead it alters the date to be a valid one (in the previous example, to 1/3/2001). If this isn't what you want, call df.setLenient( false ).
2. If the format represents a 4-digit year (yyyy) then "12/6/01" is parsed as "12/06/0001" - 1 A.D. If it is 2-digit (yy) then the year is set to be between 80 years before and 20 years after the date the SimpleDateFormat instance is created (e.g. today!). Thus if today is 1/10/01, then "30/9/21" is interpreted as "30/09/2021" and "1/10/22" is "01/10/1922". This boundary date can be altered by the set2DigitYearStart() method.
3. Years are only interpreted as per (2) if 2 digits are supplied. "1/1/1" will always be interpreted as "01/01/0001".
4. If you are using SQL (thus importing the java.sql.* package) you need to always explicitly reference the Date object as java.util.Date, since both util and sql packages contain objects called Date.
The TimeZone, Calendar and its child GregorianCalendar can do more sophisticated date arithmetic and processing, but do not deal directly with dates formatted as strings.
If you want to allow the user to enter either 2-digit or 4-digit years, try this: