如何在Java中比较日期?

例子:

日期为22-02-2010 日期2是今天07-04-2010 Date3是25-12-2010

Date3总是大于date1,而date2总是今天。如何验证今天的日期是否在日期1和日期3之间?


当前回答

试试这个

public static boolean compareDates(String psDate1, String psDate2) throws ParseException{
        SimpleDateFormat dateFormat = new SimpleDateFormat ("dd/MM/yyyy");
        Date date1 = dateFormat.parse(psDate1);
        Date date2 = dateFormat.parse(psDate2);
        if(date2.after(date1)) {
            return true;
        } else {
            return false;
        }
    }

其他回答

这段代码确定今天是在一段时间内。基于韩国地区

    Calendar cstart = Calendar.getInstance(Locale.KOREA);
    cstart.clear();
    cstart.set(startyear, startmonth, startday);


    Calendar cend = Calendar.getInstance(Locale.KOREA);
    cend.clear();
    cend.set(endyear, endmonth, endday);

    Calendar c = Calendar.getInstance(Locale.KOREA);

    if(c.after(cstart) && c.before(cend)) {
        // today is in startyear/startmonth/startday ~ endyear/endmonth/endday
    }

Date有前后两种方法,它们之间的比较如下:

if(todayDate.after(historyDate) && todayDate.before(futureDate)) {
    // In between
}

要进行包容性比较:

if(!historyDate.after(todayDate) && !futureDate.before(todayDate)) {
    /* historyDate <= todayDate <= futureDate */ 
}

你也可以试试Joda-Time,但请注意:

Joda-Time是Java SE 8之前的Java事实上的标准日期和时间库。现在要求用户迁移到java。时间(jsr - 310)。

后端端口可用于Java 6和7以及Android。

试试这个

public static boolean compareDates(String psDate1, String psDate2) throws ParseException{
        SimpleDateFormat dateFormat = new SimpleDateFormat ("dd/MM/yyyy");
        Date date1 = dateFormat.parse(psDate1);
        Date date2 = dateFormat.parse(psDate2);
        if(date2.after(date1)) {
            return true;
        } else {
            return false;
        }
    }

使用compareTo:

date1.compareTo (date2);

比较这两个日期:

  Date today = new Date();                   
  Date myDate = new Date(today.getYear(),today.getMonth()-1,today.getDay());
  System.out.println("My Date is"+myDate);    
  System.out.println("Today Date is"+today);
  if (today.compareTo(myDate)<0)
      System.out.println("Today Date is Lesser than my Date");
  else if (today.compareTo(myDate)>0)
      System.out.println("Today Date is Greater than my date"); 
  else
      System.out.println("Both Dates are equal");