Here is my target format:
19 AUG 2011
And I try to convert this string to Calendar object by following code, but variable “date” remains null..
SimpleDateFormat formatter ;
Date date = null ;
formatter = new SimpleDateFormat("dd MMM yyyy");
try {
date = formatter.parse(returnDate);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal=Calendar.getInstance();
cal.setTime(date);
Does anyone know what’s going wrong? Thank You.
FYI, exception msg:
Unparseable date: “19 Aug 2011” at java.text.DateFormat.parse(Unknown
Source)
But I don’t think it is useful…
Something is going wrong with the parsing. You aren’t finding out about it because of this:
That’s basically saying, “I don’t care what goes wrong – ignore it.” At the very least you should be logging the error, and more likely letting the exception bubble up.
Exceptions are an incredibly important diagnostic tool – don’t just catch them and ignore them.
EDIT: Now that the question’s changed, we can see the exception – but the code is still continuing as if nothing’s happened. Even if you do want to mostly ignore the exception, you need to decide what value you want
dateto have if parsing failed. Clearlynullis unhelpful – so you need to either let the exception bubble up (to let the caller know that parsing failed) or return some difference value (e.g. a default date, or today, or something like that).Now, as it happens, letting the exception bubble up makes the code simpler too. It doesn’t throw an exception on my machine, but maybe it will on yours:
Note how we don’t need to declare variables separately to assigning them values, and that now we’re letting the exception bubble up we can just assign
dateits useful value directly.My guess is that your default time zone doesn’t use “AUG” as a short month name – but I can’t really tell without seeing the exception. If that’s the case, you might want to specify the locale when constructing the formatter:
You might also want to specify a time zone.
(As an aside, Joda Time is a far superior API for date and time handling. If you’re doing any significant work with the value afterwards, I’d definitely recommend using it over
Date/Calendar.)