Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I agree with the other answers; use SimpleDateFormat to parse, if the assignment allows you to.</p> <p>You can also use the Calendar class to do something like this by switching lenient interpretation of values off, then setting the fields, and then forcing the Calendar instance to recompute it's internal counters. This will throw an exception if the field values are inconsistent. Like so:</p> <pre><code>import java.util.*; public class Test { public static void main(String[] args) { Calendar c1=new GregorianCalendar(); c1.setLenient(false); c1.set(2010,1,23); // should work: Jan. 23, 2010 c1.getTimeInMillis(); // will revalidate the calendar fields System.out.println("OK: "+c1.toString()); try { c1.set(2010,2,35); // invalid date: Feb. 35, 2010 c1.getTimeInMillis(); // revalidate... should throw exception! System.out.println("OK: "+c1.toString()); // never happens } catch(IllegalArgumentException t) { System.out.println("FAIL: "+c1.toString()); t.printStackTrace(); } } } </code></pre> <p>Here the calls to getTimeInMillis() force Calendar to revalidate its internal fields; the call will throw IllegalArgumentException if the values are inconsistent with normal Calendar time (i.e. out of range). If you'd left the default of lenient=true enabled, the second call would succeed, but you'd end up with a day in March as Calendar tries to figure out what you meant!</p> <p>The only real catch is that to do a computation like this properly, you must know what the year is so that Calendar can do leap year calculations for you to get the number of days in February correct. </p> <p>If for some reason you <em>really</em> don't care about the year, you could just hardcode a year that you know isn't a leap year... like 2009. Be sure to document that you're doing something weird like that though! It's a bit of a hack, and that's often an indication that you're doing something in a less than optimal way!</p> <p>But, as mentioned in the other answers, either SimpleDateFormat, or a little array-based lookup table is probably the easy and clean answer here.</p> <p>Hope you find this educational.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload