Akari
Akari

Reputation: 856

how to compare two dates in java in a simple way

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

Answers (6)

Graham Griffiths
Graham Griffiths

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

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

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

tostao
tostao

Reputation: 3048

Date d1, d2; This returns greatest dates: d1.after(d2) ? d1 : d2;

Upvotes: 3

ihsan kocak
ihsan kocak

Reputation: 1581

You can use Date's getTime() method and then use < >.

Upvotes: 0

Brian Agnew
Brian Agnew

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

Juvanis
Juvanis

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

Related Questions