-1

I want to give an error message if the user inputs using the wrong format. The correct format is "yyyy-MM-dd HH:mm:ss". How can I put that as a condition?

for example if (yyyy <0 ) { sout("please input correct year")}

this is the code i use for ask the user and formatting it

Scanner keyboard = new Scanner(System.in);
        String hour = "00:00:00";
        System.out.println("Please enter Date : ");
        String time = keyboard.next()+" "+ hour;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(time, formatter);
Manaar
  • 202
  • 4
  • 15
Agung Banar
  • 13
  • 1
  • 5

2 Answers2

1

You can use a regex comparison:

while input doesn't match the regex pattern
     print "Please enter date in the correct format: yyyy-MM-dd HH:mm:ss"
continue with the rest of the code

The RegEx pattern could be:

\d{4}-[01]\d-[0-3]\d [0-2]\d:[0-5]\d:[0-5]\d(?:.\d+)?Z?

You can use this site to create and test RegEx patterns

Manaar
  • 202
  • 4
  • 15
0

If the user should just enter a date (such as 2019-03-31), there is no reason why your program should be concerned with time of day too. Furthermore, your format is ISO 8601, the format that LocalDate and the other the classes of java.time parse (and also print) as their default. So you don’t need an explicit formatter.

I understand that you want a range check, which is certainly advisable. In addition, if a user enters a completely different format, parsing will throw a DateTimeParseException which you should catch and act accordingly. For example:

    LocalDate minAcceptedDate = LocalDate.of(0, Month.JANUARY, 1);
    LocalDate maxAcceptedDate = LocalDate.of(4000, Month.DECEMBER, 31);

    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please enter Date : ");
    while (true) {
        String time = keyboard.next();
        try {
            LocalDate dateTime = LocalDate.parse(time);
            if (dateTime.isBefore(minAcceptedDate) || dateTime.isAfter(maxAcceptedDate)) {
                System.out.println("Please enter a date in the range " + minAcceptedDate + " through " + maxAcceptedDate);
            } else { // OK
                break;
            }
        } catch (DateTimeParseException dtpe) {
            System.out.println("Please enter a date in format yyyy-mm-dd");
        }
    }

Example session:

Please enter Date : 
Yesterday
Please enter a date in format yyyy-mm-dd
-001-12-30
Please enter a date in format yyyy-mm-dd
5000-12-12
Please enter a date in the range 0000-01-01 through 4000-12-31
2016-09-22
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161