I’m trying to output a calendar object which also contains the time. I’ve written a method to do this using the SimpleDateFormat.
public static Calendar stringToCalendar(String string)
{
Calendar cal = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("yyyyMMdd - HHmmss");
Date date = new Date();
try {
date = formatter.parse(string);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cal.setTime(date);
return cal;
}
my input string is “20110614-15:05:00”
However it doesn’t like this value and gave me the following error:
java.text.ParseException: Unparseable date: "20110614-15:05:00"
at java.text.DateFormat.parse(DateFormat.java:337)
at transformer.Converter.stringToCalendar(Converter.java:22)
Why can it not detect the 15:05:00 as a time?
You need to make the date format you specify match the actual format of the data. In this case you’re missing the colons, and you’re expecting spaces which don’t exist. It looks like your format should be
"yyyyMMdd-HH:mm:ss".Additionally, catching and just logging an error but then continuing with the current date as if nothing had happened is almost certainly the wrong thing to do. Why not just declare that
stringToCalendarthrowsParseException?(Finally, I personally find that Joda Time is a much nicer API for date and time work. If you’re doing significant work like this, you should at least look at it and consider switching.)