如何检查字符串是否符合特定的日期格式??java

ssm49v7z  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(331)

这个问题在这里已经有答案了

如何用localdatetime解析/格式化日期(java 8)(7个答案)
上个月关门了。
屏幕格式应为:

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

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

j8ag8udp

j8ag8udp1#

String.matches 使用正则表达式模式,不理解日期格式。
实际上,您需要尝试使用 LocalDateTime.parse ,例如

相关问题