0

I have some problem. I have json file with date, where I expect "2017-05-15T19:30:00+01:00".

I want validate date from server using SimpleDateFormat. I use this format: "yyyy-MM-dd'T'HH:mm:ssZ"

When I parse expected date all looks good, but if I have invalid date, for example, "15-05-2017T19:30:00+01:00" I also don't have parse exception.

What format I should use? Thanks.

Yahor Urbanovich
  • 733
  • 1
  • 9
  • 17

1 Answers1

0

I assume you are using SimpleDateFormat Date parse(String text, ParsePosition pos). According to the documentation:

The return value is:

A Date parsed from the string. In case of error, returns null.

So an exception is not expected for your case, but a null date object.

Edit:

I just stumbled on this answer. It says that if you want to make the parsing rigorous you should use setLenient(false).

For example:

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
    sdf.setLenient(false);

    try {
        date = sdf.parse("15-05-2017T19:30:00+01:00");
        System.out.println("Rigorous date (won't be printed!): "+date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
Community
  • 1
  • 1
Doron Yakovlev Golani
  • 5,188
  • 9
  • 36
  • 60