JDBC default date format when reading a date as a string from a ResultSet

I am looking at code that basically does the following:

ResultSet rs = ps.executeQuery(); String myDateStr = rs.getString("MY_DATE"); //field is of type Date SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss'.0'"); Date myDate = sdf.parse(myDateStr); 

In some environments, the last line works, and in others, an exception is thrown. It appears that on some systems the default date format is 2013-01-25 00: 00: 00.0 and others 2013-01-25 00:00:00. The JVM, OS, and Oracle versions are different between environments (everyone uses Oracle and runs on unix).

Changing the code can be tricky. I am wondering if there is an environment variable or similar that can be configured so that the date format is returned from the rs.getString () file?

+4
source share
4 answers

Instead of using

 String myDateStr = rs.getString("MY_DATE") 

you should use

 Timestamp timestamp = rs.getTimestamp("MY_DATE"); 

JDBC / Database will handle the date conversion for you.

+3
source

try the following:

 ResultSet rs = ps.executeQuery(); Date myDate = rs.getDate("MY_DATE"); 

or that:

 ResultSet rs = ps.executeQuery(); String myDateStr = rs.getString("MY_DATE"); Date myDate = valueOf(myDateStr); 

Details on the date: http://docs.oracle.com/javase/7/docs/api/java/sql/Date.html
More about ResultSet: http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html

+3
source

If the field is of type Date , then read it as java.sql.Date and do whatever conversion you need after that. Otherwise, you will be at the mercy of the database implementation.

+2
source

For the used Oracle JDBC driver, the format is hard-coded in the driver library, so it should only be different on different systems if different versions of the drivers are used.

See my attempt to get the answer to the same question here: Where is the date format specified when reading the date as a string from the JDBC ResultSet .

(Apologies for asking a separate question, but since your question has been answered several times with the ever-useful answer "just don't do this," I tried again ...).

0
source

All Articles