简体   繁体   中英

Using Regex in String.matches in java to match a date format

Example1:
Input= 12/06/1987
output=1
Example2:
Input= 03/1/1987
output=-1

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CheckDateFormat {
    public static void main(String[] args) {
        String s1="29/02/2006";
        getvalues(s1);
    }
    public static void getvalues(String s1) {
        if(s1.matches("[0-9]{2}[/][0-9]{2}[/][0-9]{4}"))
        {
            SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
            sdf.setLenient(false);
            try {
                Date d1=sdf.parse(s1);
                System.out.println(1);
            } catch (ParseException e) {
                //e.printStackTrace();//Always going to catch block
                System.out.println(-1);
            }
        }
        else
            System.out.println(-1);
    }
}


The problem with the code is that it it always returns -1.
It always enters the catch block and gives a ParseException.
Is there any problem with the Regex?

Problem is this line:

sdf.setLenient(false);

and this date:

String s1="29/02/2006";

As 2006 wasn't a leap year making your date invalid and with lenient set to false date parse call is failing and throwing ParseException .

Problem will be fixed if you comment out sdf.setLenient(false); line:

or use a valid date:

String s1="29/02/2008";

Since 2008 was a leap year making 29th Feb a valid date.

You do not need a regex. If you get a ParseException you can return -1 else you return 1 :

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CheckDateFormat {
    public static void main(String[] args) {
        String s1="29/02/2006";
        System.out.println(getvalues(s1));
    }
    public static int getvalues(String s1) {
        SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
        sdf.setLenient(false);
        try {
            Date d1=sdf.parse(s1);
            System.out.println(1);
        } catch (ParseException e) {
            return -1;
        }
        return 1;
    }
}

Exception is thrown due to following line. Comment it off.

sdf.setLenient(false);

As the year 2006 was not leap year, using String s1="29/02/2006"; will throw a parse exception.

Try with other dates it will work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM