【问题标题】:How to check A string Matches a certain date format ?? JAVA [duplicate]如何检查字符串是否匹配某种日期格式?? JAVA [重复]
【发布时间】:2021-03-19 07:16:11
【问题描述】:

屏幕格式应该是:

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

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

【问题讨论】:

  • 这个已经讲过很多次了。了解 DateTimeFormatterLocalDateTime 课程。陷阱DateTimeParseException

标签: java datetime-format


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2022-10-23
    • 2013-02-05
    • 2016-06-07
    • 2016-10-03
    • 1970-01-01
    • 2018-04-03
    • 2016-01-12
    • 1970-01-01
    • 2011-10-06
    相关资源
    最近更新 更多