5

I have two date formats :

"yyyy-MM-dd", "dd-MM-yyyy"

But when I am trying to parse the date :"11-05-2021" , it is not throwing exception for "yyyy-MM-dd" format. Below is the thing which I am trying to do :

SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
    sdf.parse(d);
} catch (Exception e) {
    e.printStackTrace();
}

Why it is not giving the exception for "yyyy-MM-dd" format . How it can be differentiated between the two formats ?

Thanks

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
nee nee
  • 79
  • 4
  • 3
    Wow, it even parses but the result is wrong... Another reason for using `java.time`, better start yesterday! – deHaar Jun 22 '21 at 11:19
  • I’d use `if (d.charAt(2) == '-')` then it’s dd-MM-yyyy, otherwise it must be the other one. – Ole V.V. Jun 22 '21 at 11:42
  • 1
    I recommend you don’t use `SimpleDateFormat`. That class is notoriously troublesome and long outdated. Instead use `DateTimeFormatter` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 22 '21 at 18:12

0 Answers0