-3

The screen formate should be:

"dd-MM-yyyy HH:mm"

So far is have

 try
        {
            boolean correct = false;
            while(!correct)
            {
                Scanner in = new Scanner(System.in);
                System.out.print("Date: ");
                String ans = in.next();

                if(ans.matches("dd-MM-yyyy HH:mm"))
                {
                    correct = true;
                    date = ans;
                }
                else{
                    System.out.println("Please use this format (dd-MM-yyyy HH:mm)");
                }
            }
        }catch (InputMismatchException e)
        {
            System.out.println("--Please Enter an String--");
        }

What is the best way validate(check) the user has typed it in like this?

  • This has been covered many times already. Learn about `DateTimeFormatter` and `LocalDateTime` classes. Trap for `DateTimeParseException`. – Basil Bourque Dec 07 '20 at 23:57

1 Answers1

3

String.matches uses a regex pattern, and does not understand date formats.

You'll need to actually try and parse the string using LocalDateTime.parse, for example

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245