Compare a date in a given period

823 views Asked by At

I want to compare a date in a given period. I use the methods before and after. here is my method.

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

if my dateLine = "01/01/2012" and my period.getDateStart () = "01/01/2012". I return false. I do not understand why?

2

There are 2 answers

2
Vaandu On BEST ANSWER
    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);
3
Adel Boutros On

If you would kindly check the Java documentation before posting your question, you would know that the method after returns :

true if and only if the instant represented by this Date object is strictly later than the instant represented by when; false otherwise.

In your case, the dates are equal which means they are not strictly later. Thus it will return false

UPDATE:

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