2

Parsing MM/dd/yyyy HH:mm:ss e.g. 06-26-2017 03:54:26 into yyyy/MM/dd HH:mm:ss does not throw parsing exception. Instead parses the date in incorrect date. How can we handle this in Java?

Below is the code snippet :

try {
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                      .parse("06-26-2017 03:54:26");
} catch (ParseException e) {
    System.out.println(e);
}
ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • Can you show us the "incorrect" date? – nabuchodonossor Mar 06 '19 at 07:01
  • 2
    `SimpleDateFormat.setLenient(false)` –  Mar 06 '19 at 07:03
  • 1
    @nabuchodonossor - Incorrect date is "Wed Aug 09 03:54:26 IST 13" – Tejasvi Gangurde Mar 06 '19 at 07:18
  • I´m not really firm in java, but I found this question enlighting, because I learned today, that java do some kind of "guessing" if not restricted to strict date handling. – nabuchodonossor Mar 06 '19 at 07:25
  • 1
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 06 '19 at 07:47
  • @nabuchodonossor The old and troublesome `SimpleDateFormat` and other datetime classes from Java 1.0 and 1.1 show the surprising behaviour you describe. Just avoid them. The modern classes in java.time don’t (or only in very rare cases). – Ole V.V. Mar 06 '19 at 07:48
  • @a_horse_with_no_name -SimpleDateFormat.setLenient(false) worked for me. Thank you for quick response. – Tejasvi Gangurde Mar 06 '19 at 08:12
  • I took this opportunity to write a new and modern answer to the linked original question [here](https://stackoverflow.com/a/55021417/5772882). – Ole V.V. Mar 06 '19 at 11:00

0 Answers0