0

Comparing 2 dates in different format .both are in strings.

String date = "2019-01-01";         
String date1 = "Mar 13 2019 11:33 AM";

But getting error as Exception in thread "main" java.text.ParseException: Unparseable date: "Mar 13 2019 11:33 AM"

// code :       
Date date11=new SimpleDateFormat("yyyy-mm-dd").parse(date);  
System.out.println(date11);  

Date date22=new SimpleDateFormat("mmm dd yyyy HH:MM ").parse(date1);  
System.out.println(date22);  

if(date22.compareTo(date11) > 0) {
    System.out.println("date 22 is greater tehan date 11 ");
}

Expected: Parse 2 string dates in same format and then compare. Actual: Getting the below error while parsing date .

Error facing :

Exception in thread "main" java.text.ParseException: Unparseable date: "Mar 13 2019 11:33 AM"
        at java.text.DateFormat.parse(Unknown Source)
        at aaa.basic.main(basic.java:24)

Thanks in advance.

Rakesh
  • 4,004
  • 2
  • 19
  • 31
  • 4
    m is for minutes. M is for month. And SimpleDateFormat is obsolete. Stop using it. Use the classes from the java.time package. – JB Nizet Jul 15 '19 at 18:19
  • You're missing the token in your format string for AM / PM – Alex Hart Jul 15 '19 at 18:23
  • 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 `LocalDate`, `LocalDateTime` and `DateTimeFormatter`, all from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jul 15 '19 at 19:11

2 Answers2

0

you also need to specify the locale

new SimpleDateFormat("MMM dd yyyy hh:mm aa", Locale.ENGLISH).parse(date1);
Marc Stroebel
  • 2,295
  • 1
  • 12
  • 21
-1

Addressing the ParseException on the .parse() method.

Your code should give the following error:

Tue Jan 01 00:01:00 CAT 2019

Exception in thread "main" java.text.ParseException: Unparseable date: "Mar 13 2019 11:33 AM"

at java.text.DateFormat.parse(DateFormat.java:366)

at Main.main(Main.java:15)

The following date format should work. For more examples, see this.

MMM dd yyyy hh:mm aa

(credit to @MarcStrobel for locale catch);

This may be helpful. See for example.

Use the .before() or .after() methods.

Your working example will be similar to:

Date date11 = new SimpleDateFormat("yyyy-mm-dd").parse(date);  
Date date22 = new SimpleDateFormat("MMM dd yyyy hh:mm aa").parse(date1); 
if (date11.before(date22)) {
    System.out.println("date 11 is before date 22");
} else {
    System.out.println("date 11 is after date 22");
}

as noted by @DorianGray, the .compareTo() method should also work, but I prefer to be more specific before/after.

Hope it helps!

Community
  • 1
  • 1
CybeX
  • 2,060
  • 3
  • 48
  • 115