1

I get a string value by a text box in html. I want to validate that string using if condition to see if the given string is a date.

    if (matches ^\d\d\d\d((01|03|05|07|08|10|12)(30|31|[012]\d)|(04|06|09|11)(30|[012]\d)|02[012]\d)$)
    if (endsWith "0229")
         return true or false depending on the year being a leap year
    return true
return false

I fond this code by googling but contain errors and not successful.

Please help me with this matter.

hinata
  • 385
  • 1
  • 3
  • 12

2 Answers2

2

I want to validate that string using if condition to see if the given string is a date.

You should better try with parsing.You can use org.apache.commons.lang3.time.DateUtils

For Example :

String[] validFormats = new String[] {"dd.MM.yyyy", "dd.MM/yyyy" };
Date date = DateUtils.parseDate(validFormats);
//Throw ParseException if String is not parsable with given formats

Note here that there is a limitation that it can only parse if date String is in one of the allowed formats. If you don't want to use third party library. You can create your own method and use loop, try to parse one by one if you successfully get date just return date.

akash
  • 22,664
  • 11
  • 59
  • 87
1

According comments:

your String has some standard or predefined pattern?

yes like 2015-08-30

So, use SimpleDateFormat::parse(String):

Parses text from a string to produce a Date.

class MyDateUtils {
    public static boolean isValidDate(String curDate) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        // don't allow dates out of range as 2015-18-33
        format.setLenient(false);  

        Date parsedDate = null;
        try {
            parsedDate = format.parse(curDate);
        } catch (ParseException e) {}

        return parsedDate == null ? false : true;
    }
}

To execute:

MyDateUtils.isValidDate("2015-12-31"); // returns true
MyDateUtils.isValidDate("2015-18-31"); // returns false
MyDateUtils.isValidDate("2015/12/31"); // returns false
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109