比较日期和其他小的Java打趣道

问题描述:

我目前工作的一些代码,需要日期的比较如下:比较日期和其他小的Java打趣道

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

所以我的问题是穆蒂部分。

  1. 这是比较两个日期的最佳方法吗?
  2. 与“该方法必须返回类型int的结果”错误味精,什么是最好的方式去解决这个问题? (我不认为增加一个返回0;最后是非常实用的...这是我在想什么)
  3. [可选]是否有更有效的方法来编写3 if/else if语句?

谢谢你们!

貌似好方法比较日期。 对于编译错误,在catch块中重新抛出一个异常或返回一个int值。

+0

对不起,我对Java还是有点新鲜......你能解释一下“在catch块中重新抛出一个异常”吗? – user1549672 2012-08-05 03:09:09

+1

您可以添加一个“throw e”,在这种情况下,您可能需要在函数声明中声明异常(并且等同于不捕获异常)或添加“throw new RuntimeException(e )”。无论哪种方式,这将打断你的执行流程,直到某个调用者捕获到异常。 – molyss 2012-08-05 08:19:16

+0

这个工作!谢谢! – user1549672 2012-08-05 08:37:18

  1. 使用date1.compareTo(date2)
  2. 编译错误:没有默认的返回值。见点#1
  3. 从点#1:

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

是的我正在阅读一篇关于比较日期的不同方法的文章,它说日历方法更好,因为如果比较不同的sdf格式,compareTo方法将返回false。 – user1549672 2012-08-05 03:08:33

+0

但是您在这里使用一个SimpleDateFormat格式,所以这不是问题。 :) – Reimeus 2012-08-05 09:49:32