I have put together a method that is supposed to check if a given date is within a certain lower and upper limit.
It shouldn't consider the time, only the dates. It seemed to be a quite simple task but I am getting some strange behavior when debugging it.
I have tried different approaches for removing the time value from the input dates. (inDate
.) but they all seem to give me the same unexpected behavior of putting my inLeft
date before inLeft
and thus making the function result as false.
As you can see from the screenshot inLeft
and inLeft
are equal (if we ignore time) so why is int leftLimit = DateTimeComparator.getDateOnlyInstance().compare(inLeft, inDate);
resulting in 1 rather that 0?
My conclusion is that I am doing something wrong but cannot find what. Please forgive me if this is something totally obvious.
Here is my Code:
protected boolean checkDateInRange(Date inDate, Date inLeft, Date inRight) {
System.out.println("inDate = " + inDate);
System.out.println("inLeft = " + inLeft);
System.out.println("inRight = " + inRight);
int leftLimit = DateTimeComparator.getDateOnlyInstance().compare(inLeft, inDate);
int rightLimit = DateTimeComparator.getDateOnlyInstance().compare(inDate, inRight);
System.out.println("leftLimit = " + leftLimit);
System.out.println("rightLimit = " + rightLimit);
if (leftLimit > 0 || rightLimit > 0) {
return false;
}
return true;
}
I/System.out: inDate = Mon Sep 26 00:00:00 GMT+02:00 2016
I/System.out: inLeft = Mon Sep 26 20:14:13 GMT+02:00 2016
I/System.out: inRight = Mon Sep 26 00:00:00 GMT+02:00 2016
I/System.out: leftLimit = 1
I/System.out: rightLimit = 0
The problem is that leftLimit == 1, instead of 0, inDate and inLeft without the time are the same. but leftLimit still results 1.
Edit (Final Solution): According to sumandas' and Roberts solution i have written a new method that gives me the expected behaviour.
New code:
protected boolean checkDateInRange(Date inDate, Date inLeft, Date inRight) {
SimpleDateFormat simpleDateFormatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = simpleDateFormatter.format(inDate);
String leftString = simpleDateFormatter.format(inLeft);
String rightString = simpleDateFormatter.format(inRight);
if (leftString.compareTo(dateString) > 0 || dateString.compareTo(rightString) > 0)
return false;
return true;
}
I still don't understand why my initial solution should not work.