Java 日期格式 yyyy/MM/dd 的正则表达式模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24139038/
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-14 10:25:45  来源:igfitidea点击:

Regex pattern for date format yyyy/MM/dd

javaregex

提问by Krishnanunni P V

I need to validate a date with format yyyy/MM/ddusing a regex pattern. I already have a regex for the format dd/MM/yyyy.

我需要yyyy/MM/dd使用正则表达式模式验证具有格式的日期。我已经有了 format 的正则表达式dd/MM/yyyy

(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\d\d)

I'm using the validation from this link http://www.mkyong.com/regular-expressions/how-to-validate-date-with-regular-expression. I need the validation for yyyy/MM/dd. Can anyone help me?

我正在使用此链接http://www.mkyong.com/regular-expressions/how-to-validate-date-with-regular-expression 中的验证。我需要 yyyy/MM/dd 的验证。谁能帮我?

采纳答案by Krishnanunni P V

I have found the answer:

我找到了答案:

((?:19|20)\d\d)/(0?[1-9]|1[012])/([12][0-9]|3[01]|0?[1-9])

回答by Viorel Florian

Here is my take on it:

这是我的看法:

((19|20)[0-9]{2})/((0?[1-9])|1[012])/((0?[1-9])|(1[0-9])|(3[01]))

回答by Dave

Old question, I know, but as I've just had cause to do this:

老问题,我知道,但因为我有理由这样做:

\d{4}\\d{2}\\d{2}

Looks a lot neater to my eyes than the other suggestions, and works outside of the 20th/21st century (unclear if OP required this or not).

在我看来比其他建议更整洁,并且在 20/21 世纪之外工作(不清楚 OP 是否需要这个)。

However, my implementation will match for dates such as 9999/99/99 (clearly invalid) - but as a commenter suggested, SimpleDateFormatis the tool for that kind of validation, in my opinion.

但是,我的实现将匹配诸如 9999/99/99(显然无效)之类的日期 - 但正如评论者所建议的SimpleDateFormat那样,在我看来,这是进行这种验证的工具。

If OP were able to use SimpleDateFormat as well as regex, then this would suffice:

如果 OP 能够使用 SimpleDateFormat 以及正则表达式,那么这就足够了:

public static final boolean isDateValid(String date) {
    if (!date.matches("\d{4}\\d{2}\\d{2}"))
        return false;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    try {
        sdf.parse(date);
        return true;
    } catch (ParseExceptione) {
        return false;
    }
}

NB. Usual caveats about SimpleDateFormat not being thread safe etc.

注意。关于 SimpleDateFormat 不是线程安全等的通常警告。

回答by Kunal Paliwal

i think this helpful for u...

我认为这对你有帮助...

var regdate = /^(19[0-9][0-9]|20[0-9][0-9])\/(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])$/;

回答by Watchmaker

A simple regex plus a SimpleDateFormat doesn't filter a String date like "2014\26\26", then it would not suffice.

一个简单的正则表达式加上一个 SimpleDateFormat 不会过滤像“2014\26\26”这样的字符串日期,那么它就不够了。

So maybe the best approach is a fully strict regex pattern.

所以也许最好的方法是完全严格的正则表达式模式。

If you turn over your regex (Java) expression from the mkyong website you should be done. As you were already suggested:

如果你从 mkyong 网站上交出你的正则表达式(Java)表达式,你应该完成。正如您已经建议的那样:

String pattern = "((?:19|20)\d\d)/(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])";

And for extra assurance you can add a SimpleDateFormat. Here is my extra verbose approach:

为了额外保证,您可以添加 SimpleDateFormat。这是我更详细的方法:

if(stringDate.length()==10 && stringDate.matches("((?:19|20)\d\d)/(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])")){      
        Date d=null;
        String checkDate=null;
        DateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        try {
            //Also parses the String as a Date with the format "yyyy/MM/dd"
            //to be sure that the passed string is correct
            d=df.parse(stringDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (d != null) {
            //Transforms the Date into a String with the format "yyyy/MM/dd"
            checkDate=df.format(d);
            System.out.println(checkDate);
        }
    }

回答by Alex

It's regexp date format(dd.MM.yyyy). You can adapt this one for you. (((0[1-9]{1}|1[0-9]|2[0-9]).(0[1-9]|1[0-2]))|(30.(04|06|09|11))|((30|31).(01|03|05|07|08|10|12))).[0-9]{4}

它是正则表达式日期格式(dd.MM.yyyy)。你可以为你调整这个。 (((0[1-9]{1}|1[0-9]|2[0-9]).(0[1-9]|1[0-2]))|(30.(04|06|09|11))|((30|31).(01|03|05|07|08|10|12))).[0-9]{4}

回答by Vijay Anantharamu

Here is an another simple approach, write a small method that converts the string input to date and convert back the date to string. Then compare both string are equal. If equal then date is correct else its incorrect. All validations are taken care by this approach.

这是另一种简单的方法,编写一个小方法,将输入的字符串转换为日期并将日期转换回字符串。然后比较两个字符串是否相等。如果相等,则日期正确,否则不正确。所有验证都由这种方法处理。

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

public class TestDate {

    public static boolean isValidDateFormat(String value, String format) {
        Date date = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            date = sdf.parse(value);
            if (!value.equals(sdf.format(date))) {
                date = null;
            }
        } catch (Exception ex) {
            return false;
        }
        return date != null;
    }

    public static void main(String[] args) {
        String format = "yyyy/MM/dd";
        System.out.println("2017/02/31 isValidDateFormat: " + isValidDateFormat("2017/02/31", format));
        System.out.println("2017/03/31 isValidDateFormat: " + isValidDateFormat("2017/03/31", format));
        System.out.println("2017/04/31 isValidDateFormat: " + isValidDateFormat("2017/04/31", format));
        System.out.println("2017/13/31 isValidDateFormat: " + isValidDateFormat("2017/04/31", format));
        System.out.println("2017/01/35 isValidDateFormat: " + isValidDateFormat("2017/01/35", format));
        System.out.println("017/01/30 isValidDateFormat: " + isValidDateFormat("017/01/30", format));
        // output : 
        //2017/02/31 isValidDateFormat: false
        // 2017/03/31 isValidDateFormat: true
        // 2017/04/31 isValidDateFormat: false
        // 2017/13/31 isValidDateFormat: false
        // 2017/01/35 isValidDateFormat: false
        // 017/01/30 isValidDateFormat: false
    }
}

回答by SamWhan

Just for fun, I wanted to see how the regex Jon Skeet's veryvalid comment mentioned (that a regex handling leap years correctly would be horrendous) would look like. And look - he was right ;)

只是为了好玩,我想看看正则表达式 Jon Skeet提到的非常有效的评论(正确处理闰年的正则表达式将是可怕的)会是什么样子。看——他是对的;)

^
(?:(?:19|2[01])\d\d\/(?:1[02]|0[13578])\/(?:[0-2]\d|3[01]))   # 31 day months
|
(?:(?:19|2[01])\d\d\/(?:(?:11|0[469])\/(?:[0-2]\d|30)))       # 30 day months
|
(?:(?:19|2[01])(?:[02468][1235679]|[13579][01345789])|1900|2100)\/02\/(?:[01]\d|2[0-8]) # Non leap year
|
(?:(?:(?:19|21)(?!00)|20)(?:[02468][048]|[13579][26]))\/02\/(?:[01]\d|2[0-9]) # Leap year
$

See it here at regex101.

在此处查看 regex101

It tests using four alternations:

它使用四种交替进行测试:

  • 31 day months
  • 30 day months
  • February non-leap years
  • February leap years
  • 31天月
  • 30天月
  • 二月非闰年
  • 二月闰年

Note that leap years are the years that are a multiple of four. An exception to that rule are multiples of 100 exceptif it's a multiple of 400. (Phew... This is what makes it horrendous.)

请注意,闰年是四的倍数。该规则的一个例外是 100 的倍数,除非它是 400 的倍数。(呼……这就是可怕的原因。)