Question

I have a date and it's supposed pattern in string.

//True
String date ="2012-10-12 12:01:10.10.150";
String pattern = "yyyy-MM-dd hh:mm:ss.SSS";

//False
String date ="2012-10-12 12:01:10.150";
String pattern = "yyyy-MM-dd hh:mm:ss";

Now,i wanted to know whether the date variable has a proper date which satisfies a given pattern in string. In the above example True/False which I shows is the expected result.

I have tried with SimpleDateFormat(if it throws ParseException),but it will not going to work for 2nd example.

public boolean isValidDate(String date, String pattern) {
    if (date == null)
        return false;
    SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
    try {
        dateFormat.parse(date.trim());
    } catch (ParseException pe) {
        return false;
    }
    return true;
}
Was it helpful?

Solution

I think you need to use both regex and SimpleDateFormat to achieve what you want

boolean validate(String date, String pattern) throws ParseException {
    String regex = pattern.replaceAll("\\w", "\\\\d").replace(".", "\\.");
    if (!date.matches(regex)) {
        return false;
    }
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    sdf.setLenient(false);
    try {
        sdf.parse(date);
    } catch (Exception e) {
        return false;
    }
    return true;
}

OTHER TIPS

Use yyyy-MM-dd hh:mm:ss as the pattern for the second date.

String date = "2012-10-12 12:01:10";
String pattern = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date parse = sdf.parse(date);

The capital S stands for milliseconds which your second string doesn't have. See the API.

From the SimpleDateFormat.parse() Java doc:

...parsing does not necessarily use all characters up to the end of the string...

This means if your date is longer that the pattern it will still produce a valid Date instance. The other way around (e.g. your second example) the pattern is longer (more detailed) that the given date string, hence it doesn't produce a Date. Use this instead for your second example:

String pattern = "yyyy-MM-dd hh:mm:ss";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top