首页 > 解决方案 > 如何检查字符串是否匹配某种日期格式??JAVA

问题描述

屏幕格式应为:

"dd-MM-yyyy HH:mm"

到目前为止是有

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

验证(检查)用户这样输入的最佳方法是什么?

标签: javadatetime-format

解决方案


String.matches使用正则表达式模式,并且不理解日期格式。

LocalDateTime.parse例如,您需要实际尝试使用 解析字符串


推荐阅读