adrian quevada adrian quevada - 11 months ago 47
Java Question

Unparseable MMM-dd-yyyy

I will be direct with my question. I am wondering why I can't parse a fromat MMM-dd-yyyy into yyyy-MM-dd (java.sql.Date format)? Any suggestion on how I am going to convert a String into a format of (yyyy-MM-dd)?

Here is the code:

public DeadlineAction(String deadline){
putValue(NAME, deadline);
deadLine = deadline;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy MM dd");
try {
finalDate = (Date) formatter.parse(deadLine);
}catch(ParseException e) {
JOptionPane.showMessageDialog(null, e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);

Thank you


Basically, you can't parse a String in the format of MMM-dd-yyyy using the format of yyyy MM dd, it just doesn't make sense, you need one formatter to parse the value and another to format itm for example

SimpleDateFormat to = new SimpleDateFormat("yyyy MM dd");
SimpleDateFormat from = new SimpleDateFormat("MMM-dd-yyyy");

Date date = from.parse(deadLine);
String result = to.format(date)

The question that needs to be asked is, why you would bother. If your intention is to put this value into the database, you should be creating an instance of java.sql.Date (from the java.util.Date) and using PreparedStatement#setDate to apply it to your query, then letting the JDBC driver deal with it