Reputation: 33
In my application I need to compare two different dates given in below formats.
Inputs: there are 2 input dates in String format.
String actual="11/12/2012 11:26:04 AM";
String expected="21/12/2012 09:49:12 AM";
I am trying to use below java code for comparision.
SimpleDateFormat format= new SimpleDateFormat("dd/MM/YYYY hh:mm:ss a");
Date date1 = format.parse(actual);
System.out.println("Formated date1 is: "+format.format(date1).toString());
// prints : 01/01/2012 11:26:04 AM Why????
Date date2= format.parse(expected);
System.out.println("Formated date2 is: "+format.format(date2).toString());
// prints : 01/01/2012 09:49:12 AM Why????
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
if( !(cal1.compareTo(cal2)<=0))
{
result=false;
String errMsg +="Actual:"+actual+" date is not before or equal to expected:"+expected+" date\n";
System.out.println(errMsg);
}
But the above code is not working as expected. please check the wrong output mentioned in comments
I think there is something wrong with the formatting. can anyone please help me.
Upvotes: 1
Views: 810
Reputation: 11443
You can use Joda Time. It has really nice methods, like isBefore()
String actual = "11/12/2012 11:26:04 AM";
String expected = "21/12/2012 09:49:12 AM";
DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/YYYY hh:mm:ss a");
DateTime dateTime1 = fmt.parseDateTime(actual);
DateTime dateTime2 = fmt.parseDateTime(expected);
if (dateTime1.isBefore(dateTime2)) {
System.out.println("awesome");
}
Upvotes: 0
Reputation: 46428
your format should be :
SimpleDateFormat format= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
Notice year
in lowercase y
Upvotes: 5
Reputation: 94479
Try:
SimpleDateFormat format= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
The Ys should be lowercase.
Upvotes: 3