Java Dateformat Error

2.1k Views Asked by At

I am using JDatechooser netbeans swing plugin for my desktop app development. By default its dateformat is mm/dd/yy but its not the format which the db required. I need to convert it to the yyyy-mm-dd format. I tried with SimpleDateformat class and it gives me the following error: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect date value: '8/29/11' for column 'registered_date' at row 1

can anyone give me a good solution to do this properly

Thanks

2

There are 2 best solutions below

1
On BEST ANSWER
0
On

Your database doesn't require a particular date format at all - you shouldn't be inserting the data as a string in the first place. You should use a prepared statement and use setDate. Ideally you should perform as few string conversions as possible - you don't need one when getting the value out of the JDateChooser, and you don't need one when inserting into the database:

// Unfortunately you need to convert from java.util.Date to java.sql.Date
statement.setDate(1, new java.sql.Date(chooser.getDate().getTime()));

(Note that you do potentially need to bear time zones in mind, but that's a different matter... you can call a setDate overload which takes a calendar too.)

If you've been inserting (or querying) data by constructing a full SQL statement including the values, you should stop doing that right away. Not only do you have this sort of conversion issue, but you also open yourself up to SQL injection attacks. Always use a prepared statement and specify any parameter as parameters rather than including them in the SQL.