Validate a Date in Java
Date validation is a common task in Java that deal with validating a date entered by a user, or a date extracted from a file or database. This post will discuss various ways to validate a date in Java.
Date validation involves checking whether a given date is in a valid format or within a valid range. For example, suppose we have a string "07-01-2013" that represents a date in the format "dd-MM-yyyy". There are several ways to validate dates in Java:
1. Using OWASP Validator
We can use OWASP Validation to check for a US format date, which extends support for leap years. It uses the following regular expression:
To use this regular expression to validate dates, we need to import the java.util.regex package and create a Pattern object with the desired regular expression that matches the date format. Then create a Matcher object by applying the pattern to the date string and use the matches method of the matcher to check if the date string matches the pattern. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import java.util.regex.Matcher; import java.util.regex.Pattern; class Main { private static final String Date_REGEX = "^(?:(?:(?:0?[13578]|1[02])(\\/|-|\\.)31)\\1|(?:(?:0?[1,3-9]|1[0-2])(\\/|-|\\.)(?:29|30)\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:0?2(\\/|-|\\.)29\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\\/|-|\\.)(?:0?[1-9]|1\\d|2[0-8])\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$"; private static final Pattern Date_PATTERN = Pattern.compile(Date_REGEX); public static boolean dateValidator(String dateString) { Matcher matcher = Date_PATTERN.matcher(dateString); return matcher.matches(); } public static void main(String[] args) { // dd-mm-yyyy or dd/mm/yyyy or dd.mm.yyyy or // dd-mm-yy or dd/mm/yy or dd.mm.yy are valid String[] dates = {"01/15/2010", "1/15/2010", "1-15-2010", "1/15/00", "02/29/2016", "02/29/2015" }; for (String date: dates) { if (dateValidator(date)) { System.out.println(date + " is valid"); } else { System.out.println(date + " isn't valid"); } } } } |
Output:
01/15/2010 is valid
1/15/2010 is valid
1-15-2010 is valid
1/15/00 is valid
02/29/2016 is valid
02/29/2015 isn’t valid
2. Using Apache Commons DateValidator
Instead of using regex for date validation, we can also use external libraries that provide more features and flexibility for date validation. Apache Commons Validator provides a simple and convenient interface called DateValidator for validating dates in various formats and locales. To validate a date, we need to get a singleton instance of DateValidator that can validate dates using the DateValidator.getInstance() method. Then use the isValid() or validate() method to validate the given string according to the desired date format and strictness. The syntax is as follows:
boolean isValid(value, pattern)
boolean isValid(value, Locale)
boolean isValid(value, pattern, Locale)
Date validate(value)
Date validate(value, pattern)
Date validate(value, Locale)
Date validate(value, pattern, Locale)
Here is an example of how to use these methods to validate a date in Java:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import org.apache.commons.validator.routines.DateValidator; import java.util.Locale; class Main { public static boolean dateValidator(String dateString, Locale locale) { // Get an instance of DateValidator DateValidator validator = DateValidator.getInstance(); // Validate the string using the given locale return validator.isValid(dateString, locale); // or use // return validator.validate(dateString, locale) != null; } public static void main(String[] args) { String[] dates = {"01/12/2010", "1/15/2010", "1-15-2010", "02/29/2016", "02/29/2015"}; for (String date: dates) { if (dateValidator(date, Locale.US)) { System.out.println(date + " is valid"); } else { System.out.println(date + " isn't valid"); } } } } |
Output:
01/12/2010 is valid
1/15/2010 is valid
1-15-2010 isn’t valid
02/29/2016 is valid
02/29/2015 isn’t valid
The advantage of using this method is that it is convenient and reliable. It uses only one method call to validate a date in Java. It also supports different date formats and locales. However, it requires adding an external dependency to our project, which may increase the size or complexity of our project.
3. Using DateFormat and SimpleDateFormat
To use DateFormat and SimpleDateFormat to validate dates, we need to create a SimpleDateFormat object with the desired format pattern and use the parse method of the formatter to parse the date string into a Date object. Then use the format method of the formatter to format the Date object back into a string and compare the formatted string with the original string to see if they are equal. Here is an example of how to do this in Java:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; class Main { public static boolean dateValidator(String dateString, String format) { DateFormat sdf = new SimpleDateFormat(format); try { Date date = sdf.parse(dateString); String formattedDate = sdf.format(date); return formattedDate.equals(dateString); } catch (ParseException e) { return false; } } public static void main(String[] args) { String[] dates = {"01/15/2010", "1/15/2010", "1-15-2010", "02/29/2016", "02/31/2015"}; for (String date: dates) { if (dateValidator(date, "MM/dd/yyyy")) { System.out.println(date + " is valid"); } else { System.out.println(date + " isn't valid"); } } } } |
Output:
01/15/2010 is valid
1/15/2010 isn’t valid
1-15-2010 isn’t valid
02/29/2016 is valid
02/31/2015 isn’t valid
Note that it does not handles the cases where the day and month of the date string is not 2 digit. This method returns false for valid date “1/15/2010” and true for “01/15/2010”.
That’s all about validating a date in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)