SimpleDateFormat to check user date input // parsing String to dates in java
When developing user interfaces for management software you usually need to check and transform what the user inputs in order to store the values in a database or a file. Java offers different alternatives to parse a String (usually the way the user inputs values to the system) to other data types.
The class SimpleDateFormat
from the java.text
package offers a simple method to do this. You just have to call the parse(String yourDate)
method in order to get a java.util.Date instance.
Following you can find some code that explains this method and some of its particularities:
1// We create the SimpleDateFormat object with the desired pattern
2SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
3// This is very important. If you need strict parsing,
4// (i.e. January * will only have 31 days you must set this to false.
5// If you don't do this when you parse "32/01/2007" the date you'll
6// you'll get really be 01/02/2007
7sdf.setLenient(false);
8try {
9 System.out.println(sdf.parse("25/12/2022"));
10} catch (ParseException ex) {
11 ex.printStackTrace();
12}
13// This first parse has no problem, when run you will get
14// Sun Dec 25 00:00:00 CET 2022
15// in the console
16try {
17 System.out.println(sdf.parse("34/15/2002"));
18} catch (ParseException ex) {
19 ex.printStackTrace();
20}
21// In this case, the date is wrong thus we will get the corresponding
22// exception
23try {
24 System.out.println(sdf.parse("28/02/202"));
25} catch (ParseException ex) {
26 ex.printStackTrace();
27}
28// This time we will not get an exception, but in some cases we would like to get the exception,
29// because this date although valid, has an uncommon length and may be due to an input error.
30//
31// To solve the above problem, we could create the following function:
32public static Date parseDate(String date) throws ParseException{
33 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
34 sdf.setLenient(false);
35 if(date.length() != 10){
36 throw new ParseException("Date with wrong length: "+date, 0);
37 }
38 return sdf.parse(date);
39}