0

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..

1 Answers1

1

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).

Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
  • I have used this to get the time. No idea why p.m is with dots. SimpleDateFormat df = new SimpleDateFormat("hh:mm a"); Calendar mCalendar = Calendar.getInstance(); mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay); mCalendar.set(Calendar.MINUTE, minute); mCalendar.set(Calendar.SECOND, 0); Date date = mCalendar.getTime(); String time = df.format(date); @krzyk –  Jul 30 '16 at 11:36
  • @DavidWallace It parses the date, the only unknown is where is the month, is it July (7) or September(9). – Krzysztof Krasoń Jul 30 '16 at 11:41
  • @user6265109 So you have the time and format it into a string and later on you want to change it the other way around? Why? Can't you use the original date and time? – Krzysztof Krasoń Jul 30 '16 at 11:42