1

I created the following function in order to convert a String to Date but I need to catch any error while doing that and so return null.

   public static Date toDateStarted(String dateStarted) {
        Date dtStarted = null;
        SimpleDateFormat dtFormat = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
        try {
            dtStarted = dtFormat.parse(dateStarted);
        } catch (ParseException e) {
            dtStarted = null;
        }
        return dtStarted;
    }

Date dtError = toDateStarted("error/7/1 4:44:44 PM");
This returned null as expected.

Date dtWrong = toDateStarted( "2016/7/1 4:44:44 PM" );
this returned a wrong date "Tue Dec 07 16:44:44 EST 168"

In this last and important case, the input date "2016/7/1 4:44:44 PM" is in a wrong format. I am passing 2016/7/1 instead of 7/1/2016 and so I was thinking that the ParseException will occurred but never happened.

After the TRY... dtStarted = "Tue Dec 07 16:44:44 EST 168" and so I got that once returned.

The time is correct (16:44 = 4:44pm) however the Date (year, month, day) is totally wrong.

I need to avoid any convertion if the input date (dateStarted) is not as STRICT as in the SimpleDateFormat Pattern.

What should I do? Optimizations are welcome.

Geo305
  • 1,084
  • 2
  • 10
  • 16
  • Possible duplicate of [Why does SimpleDateFormat parse incorrect date?](http://stackoverflow.com/questions/15336200/why-does-simpledateformat-parse-incorrect-date) – Mike M. Jul 09 '16 at 03:26

0 Answers0