0

我想比较给定期间的日期。我使用之前和之后的方法。这是我的方法。

public boolean compareDatePeriod() throws ParseException
{
    [.....]
    if (period.getDateStart().after(dateLine)){
        if (period.getDateEnd().before(dateLine)){
            result = true;
          }
      }
    ;
    return result;
}

如果我的 dateLine = "01/01/2012" 和我的 period.getDateStart () = "01/01/2012"。我返回错误。我不懂为什么?

4

2 回答 2

1

如果您在发布问题之前请检查Java 文档,您就会知道该方法after返回:

当且仅当此 Date 对象表示的时刻严格晚于 when 表示的时刻时才为真;否则为假。

在您的情况下,日期相等,这意味着它们不是strictly later。因此它将返回false

更新:

public boolean compareDatePeriod() throws ParseException
{
    [.....]
    if (!period.getDateStart().equals(dateLine)) {
        if (period.getDateStart().after(dateLine)){
            if (period.getDateEnd().before(dateLine)){
                result = true;
              }
          }
    return result;
}
于 2012-01-06T10:18:17.977 回答
1
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    Date startDate = dateFormat.parse("01/01/2012");
    Date endDate = dateFormat.parse("31/12/2012");
    Date dateLine = dateFormat.parse("01/01/2012");
    boolean result = false;     
    if ((startDate.equals(dateLine) || !endDate.equals(dateLine))
            || (startDate.after(dateLine) && endDate.before(dateLine)))  { // equal to start or end date or with in period
        result = true;
    }   
    System.out.println(result);
于 2012-01-06T10:42:42.493 回答