-1

SimpleDateFormat seems to ignore the strings in the matching string once it has found the matching pattern.

For example: the pattern "yyyyMMddHHmm" is matching 201601251531oi which I suppose it should not. However this 20160125153133 fails which is exactly right. I tried to setLenient as true and has no effect. I know we can add another check for number of digits (regex), but is there way to strictly make this pattern only work using SimpleDateFormat alone ?

public static boolean isValidDateTimeFormat(String anyString,
                    String dateTimePattern) {
                 // here the pattern is 'yyyyMMddHHmm'
                SimpleDateFormat datePattern = new SimpleDateFormat(dateTimePattern); 
                datePattern.setLenient(false); // no difference
                try {
                    datePattern.parse(anyString);
                    return true;
                }
                catch (Exception pe){
                    return false;
                }
      }
ulab
  • 1,079
  • 3
  • 15
  • 45
  • Just do it the way you're already thinking. This is probably the best way – ControlAltDel Jan 25 '16 at 14:54
  • @keppil if it is duplicate then point those, rather than just marking as duplicate. I did search before adding this question and there are numerous questions in SimpleDateFormat and none of them I had seen provide the answer. – ulab Jan 25 '16 at 15:15
  • @ControlAltDel ok I think if no other way then this is the better way :) – ulab Jan 25 '16 at 15:16
  • Don't you agree that this is a duplicate to the question I linked to? It sounds the same to me, and the answer is the same as you got here, only more complete and with suggestions for workarounds. – Keppil Jan 25 '16 at 18:54

1 Answers1

0

No, as stated by @ControlAltDel in the comments SimpleDateFormat won't work this way. You'll either need to:

  1. Add additional validation
  2. Decide that the extra characters are "ok" and use the data that SimpleDateFormat parses out
Dave
  • 13,518
  • 7
  • 42
  • 51