如何在java中比较两个日期和时间

我有两个具有以下格式的Date对象。

 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); String matchDateTime = sdf.parse("2014-01-16T10:25:00"); Date matchDateTime = null; try { matchDateTime = sdf.parse(newMatchDateTimeString); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } // get the current date Date currenthDateTime = null; DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); Date dt = new Date(); String currentDateTimeString = dateFormat.format(dt); Log.v("CCCCCurrent DDDate String is:", "" + currentDateTimeString); try { currenthDateTime = sdf.parse(currentDateTimeString); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } 

现在我想比较上述两个日期和时间。 我应该如何在Java中进行比较。

谢谢

由于Date实现了Comparable ,因此它很简单:

 date1.compareTo(date2); 

如同Comparable合同规定的那样,如果认为date1小于/大于/大于date2 (即,在这种情况下为/之前/之后),则它将返回负整数/零/正整数。

请注意, Date还有.before().before()方法,它们将返回布尔值。

另一种选择是……

将两个日期转换为毫秒,如下所示

 Date d = new Date(); long l = d.getTime(); 

现在比较两个长值

使用compareTo()

返回值

如果参数Date等于此Date,则为0; 如果此Date在Date参数之前,则小于0的值; 如果此Date在Date参数之后,则值大于0。

喜欢

 if(date1.compareTo(date2)>0) 

另一种选择是Joda-Time 。

使用DateTime

 DateTime date = new DateTime(new Date()); date.isBeforeNow(); or date.isAfterNow(); 
  // Get calendar set to the current date and time Calendar cal = Calendar.getInstance(); // Set time of calendar to 18:00 cal.set(Calendar.HOUR_OF_DAY, 18); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); // Check if current time is after 18:00 today boolean afterSix = Calendar.getInstance().after(cal); if (afterSix) { System.out.println("Go home, it's after 6 PM!"); } else { System.out.println("Hello!"); }