This question already has answers here:
How to compare dates in Java? [duplicate]
                                
                                    (11个答案)
                                
                        
                2年前关闭。
            
        

我正在尝试编写'isPast(String dateStr)'函数,该函数接收日期字符串,如果过去则返回true,否则返回false。

private static boolean isPast(String dateStr) {
    Calendar c = GregorianCalendar.getInstance();

    int currentYear = c.get(Calendar.YEAR);
    int currentMonth = c.get(Calendar.MONTH);
    int currentDay = c.get(Calendar.DAY_OF_MONTH);
    int currentHour = c.get(Calendar.HOUR_OF_DAY);
    int currentMinute = c.get(Calendar.MINUTE);
    c.set(currentYear, currentMonth, currentDay, currentHour, currentMinute);
    Date now = c.getTime();

    SimpleDateFormat sdfDates = new SimpleDateFormat("dd/m/yyyy");

    Date date = null;
    try {
        date = sdfDates.parse(dateStr);

    } catch (ParseException e) {
        e.printStackTrace();
    }

    if (now.compareTo(date) == 1){
        System.out.println(dateStr + " date given is past");
        return true;
    }
    System.out.println(dateStr + " date given is future");
    return false;
}


我打电话给:

 String str1 = "22/04/2018";
 String str2 = "22/01/2018";
 System.out.println(isPast(str1));
 System.out.println(isPast(str2));


输出为:

22/04/2018 date given is past
22/01/2018 date given is past


这里发生了什么?这不是真的。我在这上面呆了太长时间-应该很简单,显然我的Calendar对象缺少了一些东西。

最佳答案

使用Java 8中可用的LocalDate

  public static void main(String[] args) {

    String str1 = "22/04/2018";
    String str2 = "22/01/2018";
    System.out.println(isPast(str1));
    System.out.println(isPast(str2));
  }


  private static boolean isPast(String dateStr) {

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    LocalDate dates = LocalDate.parse(dateStr, formatter);

    return dates.isBefore(LocalDate.now());
  }

07-28 03:30
查看更多