2

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) {}
Dylan Wheeler
  • 6,928
  • 14
  • 56
  • 80
  • 1
    well, what line gives you the npe... – Nanne Aug 20 '11 at 19:24
  • Where are you getting the NPE, and what do the arguments look like? A short but complete program would help... – Jon Skeet Aug 20 '11 at 19:25
  • Does my edit help with your concerns? – Dylan Wheeler Aug 20 '11 at 19:27
  • Hm, my shot is you have nulls as list elements. dates might not be null but may have elements of null. Assuming dates is really valid and not null. – tichy Aug 20 '11 at 19:27
  • 1
    If it's line 2, it has to be the `currentDate` argument that's `null`. – Jorn Aug 20 '11 at 19:29
  • may be you can post the exception stack trace ? Atleast the main lines telling exactly where the exception is being thrown .. that would definitely help, my guess is that currentDate is being passed in as null.. – Bhaskar Aug 20 '11 at 19:30

2 Answers2

3

Since you've indicated that the NullPointerException is thrown on line 2, we can deduce that you're passing in null for the currentDate argument. currentDate.getTime() is the only part of line 2 that can cause a NullPointerException.

Update:

I just wrote the following Test.java code to really understand what your problem is:

import java.util.*;
import java.text.*;

class Test {
    public static void main(String[] args) {
        Date thisDate = null;
        try {
            thisDate = (new SimpleDateFormat("MM/dd/yyyy")).parse(Calendar.getInstance().getTime().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

When I run it, I get:

java.text.ParseException: Unparseable date: "Sat Aug 20 12:42:30 PDT 2011"
    at java.text.DateFormat.parse(DateFormat.java:337)
    at Test.main(Test.java:8)

So the problem is that your SimpleDateFormat.parse() expects the month/day/year format, but the Date class's toString() 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:

Date thisDate = new Date(); // this gives you the current date
Asaph
  • 159,146
  • 25
  • 197
  • 199
  • What is `sdf`? I think it's clear that either `sdf.parse()` is returning null or throwing an Exception that you're swallowing up and doing nothing with. I would bet it's the latter. – Asaph Aug 20 '11 at 19:39
  • But that method of Date is depreciated. Is there a better way? – Dylan Wheeler Aug 20 '11 at 19:51
2

What your line:

thisDate = (new SimpleDateFormat("MM/dd/yyyy")).parse(Calendar.getInstance().getTime().toString());

does is

  • create a new Calender object (initialised with the curren time),
  • get a Date() object from it,
  • convert that to string which will use a default format like "EEE MMM d HH:mm:ss z yyyy"
  • and try to parse the result as a date with the format "MM/dd/yyyy"
  • (which will fail to parse by design, resulting in a null)

If you fix all problems in this line, the end result will be a Date object containing the current time.

A much easier way to obtain such a Date is:

thisDate = new Date();
rsp
  • 23,135
  • 6
  • 55
  • 69
  • Your description of what's happening in the code is wrong. Specifically this part: "get its number of milliseconds attribute". That never happens. What happens is this: `Calendar.getInstance().getTime()` returns a `java.util.Date` and then you're just calling `toString()` on that. You never get number of milliseconds. – Asaph Aug 20 '11 at 20:00
  • @Asaph, good catch! Updated to reflect what actual happens :-) – rsp Aug 20 '11 at 20:19
  • Now this part is wrong: `convert that to string which will use the default format "yyyy-mm-dd"`. An example of a formatted date string returned by `java.util.Date.toString()` is this: `Sat Aug 20 12:42:30 PDT 2011`. – Asaph Aug 20 '11 at 20:37