0

I want to check the existence of the date, I have int variables ( representing format ) - day( dd ), month ( MM ) and year ( YY ). Here's my code:

    SimpleDateFormat df = new SimpleDateFormat("YYMMdd");
    df.setLenient(false);

    try {
        Date d = df.parse(""+day+month+year);
    } ...

Because variables are in int I have problem when day for example can be 01 ( 1 digit in int ), or 21 ( 2 digits in int ) and I'm getting error as I have 'dd' in my format. Is there an easy way how I can use my numbers to check the validity of the date?

NGix
  • 2,542
  • 8
  • 28
  • 39
  • Didn't you mean `Date d = df.parse(""+year+month+day);`? (year first, day last) – assylias Jun 12 '13 at 19:05
  • You could change your date format to `"YYMd"` – jahroy Jun 12 '13 at 19:05
  • thanks man, "YYMd" definitely should solve my problem ;P – NGix Jun 12 '13 at 19:08
  • 3
    @Ir0nm Not really. How about 13111? Is it 11-Jan or 1-Nov? – assylias Jun 12 '13 at 19:09
  • @assylias - Good point... That's not going to work without separators. Oops! – jahroy Jun 12 '13 at 19:10
  • So it's possible to add separators 'YY:M:d' and then parse string with ':' between numbers – NGix Jun 12 '13 at 19:13
  • @Ir0nm I think you are overcomplicating it. – assylias Jun 12 '13 at 19:13
  • 1
    Please read some documentation... Everything about parsing dates is covered in depth in the API documentation. You can read it [here](http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html). However, the [answer by assylias](http://stackoverflow.com/a/17073396/778118) is definitely the easiest way to achieve your goal. – jahroy Jun 12 '13 at 19:15

2 Answers2

3

If you have the day, month and year in numeric format, it would be easier to create a date directly:

Calendar cal = Calendar.getInstance();
cal.clear(); //to set the time to 00:00:00.0000 if that is an issue
cal.set(year, month, day);
Date dt = cal.getTime();
assylias
  • 321,522
  • 82
  • 660
  • 783
1

You can pad your number strings like this:

String paddedDay = String.format("%02d", day);
jahroy
  • 22,322
  • 9
  • 59
  • 108