Search code examples
javadatetime-formatlocaldate

How to give Error message when user input wrong format of date in Java8


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);

Solution

  • 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