简体   繁体   中英

Convert String to Date - Date Validation

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.

您假设SimpleDateFormat(MM-dd-yyyyas是用户输入的默认模式,或者应该确保用户只能输入SimpleDateFormat,或者应该对isValidDate()进行更改以接受

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.

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.

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;

}
  1. The valid pattern format depends for instance on the country setting of system.

  2. You should put the content of your isValidDate() method in a try-catch block to avoid an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM