SimpleDateFormat parse(string str) doesn't throw an exception when str = 2011/12/12aaaaaaaaa?

前端 未结 7 1854
野的像风
野的像风 2020-11-27 08:06

Here is an example:

public MyDate() throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy/MM/d\");
    sdf.setLenient(false);
    St         


        
7条回答
  •  情话喂你
    2020-11-27 08:26

    To chack whether a date is valid The following method returns if the date is in valid otherwise it will return false.

    public boolean isValidDate(String date) {
    
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
            Date testDate = null;
            try {
                testDate = sdf.parse(date);
            }
            catch (ParseException e) {
                return false;
            }
            if (!sdf.format(testDate).equals(date)) {
                return false;
            }
            return true;
    
        }
    

    Have a look on the following class which can check whether the date is valid or not

    ** Sample Example**

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class DateValidCheck {
    
    
        public static void main(String[] args) {
    
            if(new DateValidCheck().isValidDate("2011/12/12aaa")){
                System.out.println("...date is valid");
            }else{
                System.out.println("...date is invalid...");
            }
    
        }
    
    
        public boolean isValidDate(String date) {
    
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
            Date testDate = null;
            try {
                testDate = sdf.parse(date);
            }
            catch (ParseException e) {
                return false;
            }
            if (!sdf.format(testDate).equals(date)) {
                return false;
            }
            return true;
    
        }
    
    }
    

提交回复
热议问题