Reputation: 1553
I am getting a null pointer exception when a user enters date in wrong format.
Method to convert String to Date
Date stringToDate(String dateString) {
Date returnDate = null;
if (dateString!= null && dateString.length() > 0 && isValidDate(dateString)) {
returnDate = dateFormat.parse(dateStr);
}
return returnDate;
}
and
boolean isValidDate(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Pattern datePattern = Pattern.compile("[0-9]{2}/[0-9]{2}/[0-9]{4}");
Matcher datePatternMatch = datePattern.matcher(date);
boolean datePatternMatchfound = datePatternMatch.matches();
if(date==null){
return false;
} else if(date!=null && date.length()>0){
if(datePatternMatchfound){
sdf.setLenient(false);
sdf.parse(date.trim());
}
return true;
} else {
return false;
}
}
I am just curious to know ....
1) what should be valid pattern for date?
2) if the user enters wrong date stringToDate method will certainly get failed and throw a null pointer exception. How to avoid that?
Any help would really be appreciated.
Upvotes: 0
Views: 2597
Reputation: 1
By using Simple date format
class we can validate if the string
is date or not. You need to make sure to set the setLenient(false) to the simple date format
object.
If it's not set you are end up with issue by rounding values.For example, a lenient GregorianCalendar interprets MONTH == JANUARY, DAY_OF_MONTH == 32 as February 1.
Example code:
http://www.vijayakumarg.co.in/2014/04/how-to-validate-date-string-in-java.html
public static boolean validateJavaDate(String strDate)
{
/*
* Set preferred date format,
* For example MM-dd-yyyy, MM.dd.yyyy,dd.MM.yyyy etc.*/
SimpleDateFormat sdfrmt = new SimpleDateFormat("MM/dd/yyyy");
sdfrmt.setLenient(false);
/* Create Date object */
Date javaDate = null;
/* parse the string into date form */
try
{
javaDate = sdfrmt.parse(strDate);
System.out.println("Date after validation: " + javaDate);
}
/* Date format is invalid */
catch (ParseException e)
{
System.out.println("The date you provided is in an " +"invalid date format.");
return false;
}
/* Return 'true' - since date is in valid format */
return true;
}
Upvotes: 0
Reputation: 16235
One thing is that you need to be more defensive in your validation method.
In the code you have shown, you do this:
Matcher datePatternMatch = datePattern.matcher(date);
before you check whether the date String is null. Pattern.matcher(null)
results in NullPointerException.
So you need to move this code within your if (date != null)
conditional block.
Aside from that, I don't see a benefit in validating the date String with a regex before validating it with a DateFormat. The regex validation is not giving you any additional benefit.
Upvotes: 1
Reputation: 4599
Correct format of date representation depends entirely on your application and user locale. You can however limit the input format to a certain format and use it to parse and format the date input.
You can catch the ParseException
thrown by the parse
method and handle invalid cases inside your catch clause.
For example your code can be simplified to following:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date stringToDate(String dateString) {
try {
Date returnDate = sdf.parse(dateString);
// do something with returnDate, if necessary
return returnDate;
} catch(ParseException e) {
// Date is not valid, handle invalid cases here..
return null; // Not a good practice, you probably would throw an Exception
}
}
And you can use the same formatter to display your values in the user interface by calling sdf.format(someDate)
method and getting the String representation.
Upvotes: 1
Reputation: 10241
you are assuming the SimpleDateFormat(MM-dd-yyyyas the default pattern the user will input, either you should make sure your user can only enter in SimpleDateFormat, or you should make changes in isValidDate() to accept
Upvotes: 2
Reputation: 204756
The valid pattern format depends for instance on the country setting of system.
You should put the content of your isValidDate()
method in a try-catch block to avoid an exception.
Upvotes: 0