How can I format, display, parse and update a java.sql.Date? Code examples would be helpful.

Joe Sam Shirah

As several responders noted, java.sql.Date is a subclass of java.util.Date, with hour, minute, second and millisecond values set to zero. The various databases differ in their expectation of the exact form of the value to be sent to update/insert a date column. JDBC handles this by means of an escape in the form {d 'yyyy-mm-dd'}. That is how one would send it in a straight ahead VALUES clause or 'SET xxx =' phrase for a Statement. As is often the case, a prepared statement is very helpful; One can create a java.sql.Date and use PreparedStatement.setDate(), which will handle this format for you. In any event, the driver is responsible for the final format acceptable to the specific database.

Date retrieval is straightforward, just use ResultSet.getDate().

How do I display and parse a date? gives code to display and retrieve Date information.

If the date value you need is not immediately available as a long, the Calendar, and specifically the GregorianCalendar, class can be used. For examples and information, see How can I get yesterday's date? and How can I generate a java.sql.Timestamp from text fields formatted as MM/DD/YYYY and/or HH:MM:SS ( Month/Day/Year - Hours/Minutes/Seconds )?

Thanks to

Arif Amjad

Jorge Jordão

CJ Jouhal

Dawei Jiang

Luis F. Canals Samaniego

for contributing to this answer.

About | Sitemap | Contact