title: Check a date for different formats
body: <p>I'm trying to find an elegant way to find out if the format of a date satisfies at least one of a list of given formats. Concrete I have to validate a date against these 3 formats: YYYY, YYYY-MM and YYYY-MM-dd.</p>
  
  <p>I tried with an example found in another thread, but it doesn't work:</p>
  
  <pre><code>private boolean checkDateFormat( String dateString )
      {
          String[] possibleDateFormats = new String[] { "yyyy", "yyyy-MM", "yyyy-MM-dd" };
  
          boolean isValid = false;
  
          for ( String possibleDateFormat : possibleDateFormats )
          {
              try
              {
                  SimpleDateFormat simpleDateFormant = new SimpleDateFormat( possibleDateFormat );
                  simpleDateFormant.setLenient( false );
                  simpleDateFormant.parse( dateString.trim() );
                  isValid = true;
              }
              catch ( ParseException pe )
              {
              }
          }
  
          return isValid;
      }
  </code></pre>
  
  <p>Another way is to use regex, but it will be quite complicated to cover all the possibilities.</p>
  
  <p>Still another way is to parse the string and separately check the year, month and day. Something like this:</p>
  
  <pre><code>String[] parts = dateString.split("-");
          boolean y = validateY(parts[0]);
          boolean m = parts.length&gt;1 ? validateM(parts[1]) : true;
          boolean d = parts.length&gt;2 ? validateD(parts[2]) : true;
  
          return y &amp;&amp; m &amp;&amp; d;
  </code></pre>
  
  <p>But I find it not so "elegant".</p>
  
  <p>Other ideas?</p>
  
  <p>EXAMPLES (why code 1 doesn't work):</p>
  
  <pre><code>String[] possibleDates = new String[] { "999", "1001", "2001", "1", "123-3", "1234-13", "2015-12-31", "2015-13-31", "2015-12-32", "1-1-1" };
  
  for (String date : possibleDates)
  {
      System.out.println(date + " : " + checkDateFormat(date));
  }
  </code></pre>
  
  <p>OUTPUT(with and without break):</p>
  
  <pre><code>999 : true
  1001 : true
  2001 : true
  1 : true
  123-3 : true
  1234-13 : true     &lt;- 13 months??
  2015-12-31 : true
  2015-13-31 : true  &lt;- 13 months??
  2015-12-32 : true  &lt;- 32 days??
  1-1-1 : true
  </code></pre>
  
  <p>EXAMPLE with Kartic code:</p>
  
  <pre><code>String[] possibleDateFormats = new String[] { "yyyy", "yyyy-MM", "yyyy-MM-dd" };
  String[] possibleDates = new String[] { "999", "1001", "2001", "1", "123-3", "1234-13", "2015-12-31", "2015-13-31", "2015-12-32", "1-1-1", "0-00-0" };
  
  boolean isDate = false;
  
  for ( String date : possibleDates )
  {
      for ( String strDate : possibleDateFormats )
      {
          isDate = isValidDate( date, strDate );
          if ( isDate )
          {
              break;
          }
      }
      System.out.println(date + " :- " + isDate);
  }
  </code></pre>
  
  <p>The output is the same...</p>