Home > Back-end >  Validate a date in a string java (block errors like Feb 30)
Validate a date in a string java (block errors like Feb 30)

Time:10-30

Im trying to do a connection with a database in Java using OOP and DAO pattern with MySQL and need to validate a date string in java and insert it into MySQl, the connection is fine the problem is the validation. I have to use Strings in both because thats what i was asked for but it doesnt recognize months like february or the ones with 30 days i tried with a while but apparentrly it can be done with the method im usinng (TemporalAccesor for unary operator ERROR). I also have to calculate the age of the person based on that date but since is a string, i cant figure out how to connect it with the date of the computer.

Thanks for any help, really need it

Method that throws the exception but allows Feb-31 or Sep-31: I call it on the method where I fill all the other data and works well except for that detail Also tried a regex but i saw is not convenient and doesnt catch that either

private static void FechaNacV(){

String date;
        
        Scanner sc = new Scanner(System.in);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu/MM/dd");
        date = sc.nextLine();
        try {

            formatter.parse(date);
            System.out.println("Valid date");
        } catch (Exception e) {
            
            System.out.println("Invalid Date, try yyyy/mm/dd format again");
            FechaNacV();
        }
    } 

CodePudding user response:

ResolverStyle.STRICT

The default resolver style in DateTimeFormatter will adjust your invalid 31st of February to the appropriate 28th or 29th.

If you want to avoid that tolerant adjustment, specify a different resolver style.

    DateTimeFormatter
        .ofPattern( "uuuu/MM/dd" )
        .withResolverStyle( ResolverStyle.STRICT ) ;  // Be strict: Reject 31st of February.

Call parse on the LocalDate class rather than the DateTimeFormatter class.

LocalDate ld = null ; 

String input = "2022/02/31" ;
DateTimeFormatter formatter = 
    DateTimeFormatter
        .ofPattern( "uuuu/MM/dd" )
        .withResolverStyle( ResolverStyle.STRICT ) ;  // Be strict: Reject 31st of February.
try {
    ld = LocalDate.parse( input , formatter ) ;
} catch ( DateTimeParseException e ) {
    System.out.println( e ) ;
}
System.out.println( ld ) ;

See this code run at Ideone.com.

java.time.format.DateTimeParseException: Text '2022/02/31' could not be parsed: Invalid date 'FEBRUARY 31'

null

  • Related