lunes, 21 mayo 2007
SimpleDateFormat to check user date input // parsing String to dates in java
« Numbers to Strings with custom symbols // DecimalFormat - DecimalFormatSymbols | Main | JTable, detecting selection changes // ListSelectionListener /*Selection Changed Event*/ »When developing user interfaces for management software you usually need to check what the user inputs in order to store the values in a database or a file. Java offers different alternative to parse String (normally the way user inputs values to the system) to other data types.
The class SimpleDateFormat from the package java.text offers a simple method to do this. You just have to call parse(String youDate) in order to get a java.util.Date.
Following you can find some code which explains this method and some of its particularities:
/* We create the SimpleDateFormat object with the desired patter */ SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); /* This is very important. If you need strict parsing, (i.e. January * will only have 31 days you must set this to false. * If you don't do this when you parse "32/01/2007" the date you'll * you'll get really be 01/02/2007*/ sdf.setLenient(false); try { System.out.println(sdf.parse("25/12/2022")); } catch (ParseException ex) { ex.printStackTrace(); } /* This first parse offers no problem, when run you will get * Sun Dec 25 00:00:00 CET 2022 * in the console*/ try { System.out.println(sdf.parse("34/15/2002")); } catch (ParseException ex) { ex.printStackTrace(); } /* In this case, the date is wrong thus we will get the correspondant * exception */ try { System.out.println(sdf.parse("28/02/202")); } catch (ParseException ex) { ex.printStackTrace(); } /* This time we will not get an exception, but in some cases we would like to get the exception, because this date although valid, has an uncommon length and may be due to an input error.*/ /*To solve the above proble, we could create the following function:*/ public Date parseDate(String date) throws ParseException{ SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); sdf.setLenient(false); if(date.length() != 10){ throw new ParseException("Date with wrong length: "+date, 0); } return sdf.parse(date); }
Technorati Tags: java j2se SimpleDateFormat Date String parse ParseException throws throw Exception lenient setLenient
Posted by at 11:09 AM in Java
[Trackback URL for this entry]