0

I need to check the validity of date against a specified format. After googling, I found one:

public static boolean isThisDateValid(String dateToValidate, String dateFromat){

        SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
        sdf.setLenient(false);
        ParsePosition position = new ParsePosition(0);  
        Date date = sdf.parse(dateToValidate,position);
        return date != null && position.getIndex() == dateFromat.length();

}

but it is not working..When I ran this, it returned true instead of false.Month value specified is invalid i.e. 13

System.out.println(isThisDateValid("20101331","yyyymmdd"));

Did I miss anything?

4

3 回答 3

8
yyyymmdd

should be

yyyyMMdd

note MM for Month and mm is for Minutes

于 2013-01-21T11:46:58.413 回答
7

Use capital M for months:

System.out.println(isThisDateValid("20101331","yyyyMMdd"));

This invalid test date will return false as expected as you've called setLenient(false)

Date Format doc

于 2013-01-21T11:47:05.713 回答
1

您应该使用“yyyyMMdd”而不是“yyyymmdd”

这里提供了解释。

另外,为什么在您的问题中,月份值被分配给 13?

于 2013-01-21T12:01:24.907 回答