I have this code and when I run the script, I pass in valid parameters, but I keep on getting a NPE.
Help?
Code:
private static Date getNearestDate(List<Date> dates, Date currentDate) {
long minDiff = -1, currentTime = currentDate.getTime();
Date minDate = null;
if (!dates.isEmpty() && currentDate != null) {
for (Date date : dates) {
long diff = Math.abs(currentTime - date.getTime());
if ((minDiff == -1) || (diff < minDiff)) {
minDiff = diff;
minDate = date;
}
}
}
return minDate;
}
I get the NullPointerException from line 2 of the code above and I use the following code to pass in thisDate as the currentDate variable.
Date thisDate = null;
try {
thisDate = (new SimpleDateFormat("MM/dd/yyyy")).parse(Calendar.getInstance().getTime().toString());
} catch (Exception e) {}
Since you’ve indicated that the
NullPointerExceptionis thrown on line 2, we can deduce that you’re passing innullfor thecurrentDateargument.currentDate.getTime()is the only part of line 2 that can cause aNullPointerException.Update:
I just wrote the following
Test.javacode to really understand what your problem is:When I run it, I get:
So the problem is that your
SimpleDateFormat.parse()expects the month/day/year format, but theDateclass’stoString()method is giving you something different.It seems as though all you really want is the current date. Why bother formatting it? Just trim it down to this and be done with it: