1

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?

3

6 Answers 6

6

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.

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

3 Comments

Why would someone needs vendor for this while Date class has before() and after() docs.oracle.com/javase/6/docs/api/java/util/…
Whilst Joda is a good suggestion, I think the issues presented in this question are more fundamental
@elbek Ok, you can handle it with Date API. What if the OP comes tomorrow and asks about how long one date is earlier or after than the other one? Can your 'Date' help here? So take a look at Joda.
6

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

Comments

3

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

Comments

2

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

1 Comment

fixed for completeness
0

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

Comments

0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.