Reputation: 856
I want to know if there is a simple way to compare two dates of this format for example :
Wed, 31 Jul 2013 09:31:51
Mon, 05 Aug 2013 10:18:24
and display the greatest date?
Upvotes: 1
Views: 280
Reputation: 2216
first parse the string into a Date object using a SimpleDateFormat :
String dateStringA = "Wed, 31 Jul 2013 09:31:51";
String dateStringB = "Mon, 05 Aug 2013 10:18:24";
SimpleDateFormat parserSDF = new SimpleDateFormat("EEE, DD MMM yyyy HH:mm:ss");
Date dateA = parserSDF.parse(dateStringA);
Date dateB = parserSDF.parse(dateStringB);
if (dateA.compareTo(dateB) > 0) {
System.out.println("A bigger");
}
then compare the Date objects using compareTo method
Upvotes: 2
Reputation: 35557
This will work for you
DateFormat df=new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
Date date1=df.parse("Wed, 31 Jul 2013 09:31:51");
Date date2=df.parse("Mon, 05 Aug 2013 10:18:24");
System.out.println(date1.after(date2) ? date1 : date2);
Upvotes: 0
Reputation: 272287
I would check the documentation, which shows that Date implements Comparable<Date>
and so
date1.compareTo(date2);
will do what you want. You may wish to ensure that date1
is not null.
If your dates are (in fact) Strings, then use SimpleDateFormat's parse()
method to convert from strings to dates, and then perform that comparison.
As others have suggested, Joda is a better date/time library (better API and threading performance).
Upvotes: 6
Reputation: 25950
I'd suggest you to use Joda library. Using the date info you have, create DateTime
instances and call isBefore()
method to determine which one comes first.
Upvotes: 6