1

I am doing Validation of Date format where inputs:

    dateFormat                    | dateString                  |Excepted OP|output
    "yyyyMMdd"                    |"20180909T10:00.000z"        |false      |true

    "yyyymmdd"                    |"20180909T10.000z"           |false      |true

    "yyyy-MM-ddhh:mm:ss"          |"20180909T00:00:00.000z"     |false      |false

Code:

    formatter.setTimeZone(defaultTimeZone);
    formatter.applyPattern(dateFormat);

    try {
        formatter.setLenient(false);
        formatter.parse(dateString.replaceAll("Z$", "+0000"));
    } catch (Exception e) {
           e.printTrackTrace();
    }

My question is why SimpleDateFormat is parsing case:1 and Case:2. I don't want them to parse these dates. As I already setLenient to false. Still, they are parsing these dates and returning true.

In Case 1 and Case 2: when I am passing different format of Date (i.e UTC/ISO). I want to get failed because that was not the format I am expecting.SimpleDateFormat is considering time in ("yyyy-MM-dd") format. Which I don't want. That's why I have used setLenient(false) but that doesn't help anything.

Can someone please answer why this is happening and how should I fix this.

NDesai
  • 1,741
  • 2
  • 12
  • 16
  • 2
    Because that's how SImpleDateFormat works: it doesn't fail if there are still characters left in the string after it has found what it needed. You shouldn't use SimpleDateFormat anyway. Use the java.time classes. – JB Nizet Nov 09 '18 at 16:51
  • I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Nov 09 '18 at 17:16
  • 1
    @JBNizet Yes understood. java.time handled these test cases very well! I can not perform the validations I want using SimpleDateFormat. DateTimeFormatter is better. Thank You. – NDesai Nov 09 '18 at 20:35

0 Answers0