Search code examples
javasimpledateformatparseexception

ParseException while parsing string to date


I want to parse string format "9/7/2016 07:40 p.m." into date. But I am getting parse exception. I tried using two three formats. But still getting the Exception.

I want to compare this parsed date with current date.

     SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z",Locale.ENGLISH);

                    String upcomingEventDateTime = eventDate + " " + eventTime;

                    eventDateTime = df.parse(upcomingEventDateTime);

                    int compare = now.compareTo(eventDateTime);

                    if (compare == 1) {

                        upComingTasks++;
                    }

Which format I should use to parse this string? Thank you..


Solution

  • Please read SimpleDateFormat javadocs for the format specification, yours is completely wrong.

    Here's a working one:

    new SimpleDateFormat("d/M/yyyy hh:mm a",Locale.ENGLISH).parse("9/7/2016 07:40 pm")
    

    With slight change, "p.m." is not recognized by SimpleDateFormat, so you have to use PM/AM (without dots).