I have this code that formats the date to this pattern dd-MM-yyyy:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S");
sdf.applyPattern("yyyy-MM-dd");
Date date_out = null;
try {
date_out = sdf.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sdf.format(date_out);
However when I change separator from “-” to white space or slash “/” I get NullPointerEcxeption on the format() line. Does SimpleDateFormat accept white space or any other character as date separators?
The issue is probably that
sdf.parse(date);will be null ifdatedoes not match the pattern. If you change the pattern of the SimpleDateFormat object but don’t change the format of the date you are parsing the ParseException will be thrown anddate_outwill be null.sdf.format()will then throw a NullPointerException when you try to format the null string.Based on your comment I think a bit more explanation is required with some examples – so I’m editing my answer appropriately…
SimpleDateFormat applyPattern changes the pattern of the SimpleDateFormat object it acts in the same way as the string in the constructor does, that is, it tells the Formatter which pattern to expect / use for output.
For what I think you want, you need two SimpleDateFormatters, an input one and an output one.
eg.
Having said that I guess you could put applyPattern after the parsing, and before the output like so…
Hope this helps a bit more.