0

I have the below java code, it works if user input date of the specified format e.g 2011-11-11 but the program crashes when user enters plain text e.g 'hello', 'yes'. The code compares user input date with current date and perform action. How do I check to make sure that user enter date and not plain text before the program can continue. Here is the code:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
System.out.println("Enter valid date e.g yyyy-mm-dd: ");
String date = sn.next();
LocalDate startDate = LocalDate.parse(date, formatter); //I don't want the program to accept 'startDate' as test, it should be date of specified förmat before jumping to try and catch.
LocalDateTime lt = LocalDateTime.now();
LocalDate currentDate = lt.toLocalDate(); // for type match, I removed time stamp from the localdatetime
try {
    for (obj result : list) {
        if (startDate.isBefore(currentDate)) {
            System.out.println(result);
        } else {
            System.out.println("");
        } 
   }
} catch (DateTimeException e) {
    System.out.println ( "ERROR: " + e );
}
Bernardo Duarte
  • 3,112
  • 4
  • 15
  • 29
Pleasure
  • 219
  • 2
  • 14
  • 1
    If I understand you correctly: if the user inputs something that doesn't match date format you don't want to run this code at all, you want to reject the input and tell the user to enter a valid date before moving on? – SylarBenes Jan 08 '20 at 15:17
  • Where is the user input coming from? What class is `sn`? – SylarBenes Jan 08 '20 at 15:17
  • The format you are requiring agrees with ISO 8601 and is the default format of `LocalDate`. So you can do without the formatter and just use the 1-arg `parse` method: `LocalDate startDate = LocalDate.parse(date);`. – Ole V.V. Jan 09 '20 at 20:18

3 Answers3

3

You can catch the DateTimeParseException(which is thrown in case of invalid date), in a loop.

LocalDate startDate = null;

while(true) {
    System.out.println("Enter valid date e.g yyyy-mm-dd: ");
    String date = sn.next();
    try {
        startDate = LocalDate.parse(date, formatter);
        break;
    } catch(DateTimeParseException ex) {
        System.out.println("Invalid date entered!");
    }
}
Dimitris Fousteris
  • 1,051
  • 7
  • 11
3

You can use regex to take inputs in date. Then convert string to date. See sample code:

System.out.print("Please enter Date: ");
String date = console.nextLine();
while(!date.matches("([0-9]{2})\\([0-9]{2})\\([0-9]{4})")) {
    System.out.println("Please enter correct date format");
    date = console.nextLine();
}

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date = LocalDate.parse(date, formatter);

There are many ways to convert string to date you can use any of ways. see this link for reference (Converting string to date using java8)

Umar Tahir
  • 478
  • 4
  • 16
  • 1
    I got error using your match format but when I used this: ^\\d{4}\\-(0[1-9]|1[012])\\-(0[1-9]|[12][0-9]|3[01])$ your solution worked. – Pleasure Jan 08 '20 at 15:52
1

Trap DateTimeParseException

Surround your call to LocalDate.parse with a try-catch to trap for the DateTimeParseException thrown when encountering bad input text.

try{
    ld = LocalDate.parse( input ) ;
} catch ( DateTimeParseException e ) {
    … handle bad input from user
}
Basil Bourque
  • 218,480
  • 72
  • 657
  • 915