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

5
  • and what is "the Exception" ? Commented Jul 30, 2016 at 10:59
  • unparsble date at offset 0. @Stultuske Commented Jul 30, 2016 at 11:05
  • since we have no possible way of knowing what eventDate and eventTime are, what exactly do you expect us to do? Commented Jul 30, 2016 at 11:06
  • @Stultuske The question says quite clearly what string the OP is trying to parse. Commented Jul 30, 2016 at 11:11
  • @user6265109 The Javadoc for SimpleDateFormat lists all the formatting symbols. You just need to pick the ones that match what you've got in your string. Commented Jul 30, 2016 at 11:12

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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
@DavidWallace It parses the date, the only unknown is where is the month, is it July (7) or September(9).
@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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.