Even though there are many fancy calendar inputs on the internet, sometimes, the easiest way to let simple users to input date in web application is by using 3 drop downs: day, month and year. On the server side, we combine these 3 values to create a proper date instance. But, before converting these 3 values to date we need to make sure, the values create a valid date. There are few cases in which an invalid date can be inputted. For example, when a month with 30 days is selected along with day: 31.
Validating that the 3 values: day, month, year really constructs a proper date is an easy task in Java. But, the idea behind it, is not as trivial as it looks. The calendar class can create date instance from day, month and year, but it doesn’t make sure the values are in the range. For example, day with values 33 can be accepted without an exception being raised.
In order to make sure a date is valid we will do a small trick:
- Construct a string date representation for the inputted values: day, month, year (we can choose any format).
- Convert the string date to a java date instance by using a date formatter.
- Convert the date back to a string again.
- Check the original string we built against the converted date.
If both strings are equal, that means date is valid.
Here is the Java code that does the task:
package com.bashan.blog.date;import org.apache.commons.lang.StringUtils;import java.util.Date;import java.text.SimpleDateFormat;import java.text.Format;import java.text.ParseException;public class DateUtil {public static boolean isDateValid(int day, int month, int year){try{String date = StringUtils.leftPad(day + "", 2, "0") + "/" + StringUtils.leftPad(month + "", 2, "0") + "/" + year;String dateFormat = "dd/MM/yyyy";Date dateSimple = new SimpleDateFormat(dateFormat).parse(date);Format formatter = new SimpleDateFormat(dateFormat);return date.equals(formatter.format(dateSimple));}catch (ParseException e){return false;}}}Note that this code uses StringUtils.leftPad method, which is part of Apache Commons Lang project.
Saturday, October 31, 2009
Date validation with Java
Labels:
date,
java,
validate,
validation
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment