user1549672
user1549672

Reputation: 486

Comparing Dates & other little java quips

I am currently working on some code that requires a comparison of dates as follows:

public int compare(ItemLocation o1, ItemLocation o2) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
                Date date1 = sdf.parse(o1.getDatePublished());
                Date date2 = sdf.parse(o2.getDatePublished());
                Calendar cal1 = Calendar.getInstance();
                Calendar cal2 = Calendar.getInstance();
                cal1.setTime(date1);
                cal2.setTime(date2);
                if(cal1.equals(cal2)) { 
                    return 0; 
                } else if(cal1.before(cal2)) {
                    return -1;
                } else if(cal1.after(cal2)) {
                    return 1;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

So my question is muti-part.

  1. is this the best method to go about comparing 2 dates?
  2. with the "the method must return a result of type int" error msg, what is the best way to go about fixing this? (I don't think that adding a return 0; at the end is very practical...which is what I was thinking)
  3. [optional] is there a more efficient way to write the 3 if/else if statements?

Thanks guys!

Upvotes: 0

Views: 80

Answers (2)

Reimeus
Reimeus

Reputation: 159754

  1. Use date1.compareTo(date2)
  2. Compile error: No default return value. See point #1
  3. From point #1:

    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
    Date date1 = sdf.parse(o1.getDatePublished());
    Date date2 = sdf.parse(o2.getDatePublished());
    return date1.compareTo(date2);
    

Upvotes: 1

molyss
molyss

Reputation: 256

Looks like the good method to compare dates. For the compilation error, rethrow an exception in your catch block or return an int value.

Upvotes: 1

Related Questions