使用 Java 进行日期比较

2022-09-01 09:40:31

我有两个日期:

  1. toDate(用户输入格式)MM/dd/yyyy
  2. currentDate(由以下方式获得)new Date())

我需要与 进行比较。我必须仅在 等于或大于 时显示报告。我该怎么做?currentDatetoDatetoDatecurrentDate


答案 1

使用 比较日期更容易。以下是您可以执行的操作:java.util.Calendar

Calendar toDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
toDate.set(<set-year>,<set-month>,<set-day>);  
if(!toDate.before(nowDate)) {
    //display your report
} else {
    // don't display the report
}

答案 2

如果您设置使用 Java Dates 而不是 JodaTime,请使用 java.text.DateFormat 将字符串转换为 Date,然后使用 .equals 比较两者:

我差点忘了:在比较它们之前,您需要将当前日期的小时,分钟,秒和毫秒归零。我在下面使用了一个日历对象来执行此操作。

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;

// Other code here
    String toDate;
    //toDate = "05/11/2010";

    // Value assigned to toDate somewhere in here

    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
    Calendar currDtCal = Calendar.getInstance();

    // Zero out the hour, minute, second, and millisecond
    currDtCal.set(Calendar.HOUR_OF_DAY, 0);
    currDtCal.set(Calendar.MINUTE, 0);
    currDtCal.set(Calendar.SECOND, 0);
    currDtCal.set(Calendar.MILLISECOND, 0);

    Date currDt = currDtCal.getTime();

    Date toDt;
    try {
        toDt = df.parse(toDate);
    } catch (ParseException e) {
        toDt = null;
        // Print some error message back to the user
    }

    if (currDt.equals(toDt)) {
        // They're the same date
    }