Reputation: 1638
I have a date stored in my database as a string 14/08/2010. I want to parse it into a date in order to compare it with the current date. This is what I did but it doesn't compile I don't know why:
try{
date = new SimpleDateFormat("dd/MMM/yyyy").parse(rs.getString(2));
System.out.println(rs.getString(2));
}catch(ParseException s){
s.printStackTrace();
}
It prints this error:
java.text.ParseException: Unparseable date: "14/08/2010"
I tried changing the date format to dd/MM/yyyy but I have the same problem.
Upvotes: 1
Views: 71
Reputation: 308763
You don't know if the problem is with your date parser or the SQL ResultSet
.
A debugger will tell you quickly where the problem lies.
I strongly agree with those people who argue that you should not save a DATE in a CHAR column.
I'd write it this way to give myself a chance.
private static final DateFormat DEFAULT_DATE_FORMAT;
static {
DEFAULT_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
DEFAULT_DATE_FORMAT.setLenient(false);
}
// Your method snippet
try {
while (rs.next()) {
String dateAsStr = rs.getString(2);
Date date = DEFAULT_DATE_FORMAT.parse(dateAsStr);
System.out.println(DEFAULT_DATE_FORMAT.format(date));
}
} catch(ParseException e) {
e.printStackTrace();
} finally {
// Don't forget to close your resources in finally block.
close(rs);
close(statement);
}
Upvotes: 1
Reputation: 1135
Depending on field definition and Database it is possible that you get "14/08/2010____" instead of "14/08/2010".
On Oracle for instance returns a string filled with spaces when the DB field ist defined as CHAR.
With CHAR(24) you will always get a string with the length of 24 characters.
Try trim.
Upvotes: -1
Reputation: 46841
You should use dd/MM/yyyy
as per the Date string 14/08/2010
MMM
matches Month name such as Jan
, Feb
Read more about SimpleDateFormat Patterns
I tried
Date date = new SimpleDateFormat("dd/MMM/yyyy").parse("14/08/2010");
that results into
Exception in thread "main" java.text.ParseException: Unparseable date: "14/08/2010"
at java.text.DateFormat.parse(Unknown Source)
Upvotes: 3