Java 如何检查正确的日期格式模式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30507579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:43:56  来源:igfitidea点击:

How to check correct date format pattern?

javadateformat

提问by Sitansu

I am facing issue related to date format pattern. Suppose user gives wrong input like this '200000-05-16'and I have format like this mm/dd/yyyy. I want to check format in java class the input date is wrong.

我面临与日期格式模式相关的问题。假设用户提供了这样的错误输入,'200000-05-16'而我有这样的格式mm/dd/yyyy。我想检查java类中的格式输入日期错误。

How is it possible to do in java?

在java中怎么做?

采纳答案by romfret

Here is two solutions. I recommend the secondone (the mkyong tutorial).

这里有两个解决方案。我推荐第二个(mkyong 教程)。

Solution 1(Regexp)

解决方案 1(正则表达式)

String datePattern = "\d{2}-\d{2}-\d{4}";

String date1 = "200000-05-16";
String date2 = "05-16-2000";

Boolean isDate1 = date1.matches(datePattern);
Boolean isDate2 = date2.matches(datePattern);

System.out.println(isDate1);
System.out.println(isDate2);

Output :

输出 :

false
true

The pattern is not the better one because you could pass "99" as a month or a day and it will be ok. Please check this post for a good pattern : Regex to validate date format dd/mm/yyyy

该模式不是更好的模式,因为您可以将“99”作为一个月或一天通过,它会没问题。请检查这篇文章以获得一个好的模式:正则表达式验证日期格式 dd/mm/yyyy

Solution 2(SimpleDateFormat)

解决方案 2(SimpleDateFormat)

This solution take a SimpleDateFormat to check if it is valid or not. Please check this link for a complete and great solution : http://www.mkyong.com/java/how-to-check-if-date-is-valid-in-java/

此解决方案采用 SimpleDateFormat 来检查它是否有效。请查看此链接以获取完整且出色的解决方案:http: //www.mkyong.com/java/how-to-check-if-date-is-valid-in-java/

回答by folkol

Try to parse it, if it fails - the format was not correct.

尝试解析它,如果它失败 - 格式不正确。

Keep in mind that SimpleDateFormatis not thread safe, so do not reuse the instance from several Threads.

请记住,SimpleDateFormat不是线程安全的,因此不要重用来自多个线程的实例。

回答by Hung Tran

import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;

public class TestDate {

    public static boolean isValid(String value) {
        try {
            new SimpleDateFormat("dd/mm/yyyy").parse(value);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }
}