Tim
Tim

Reputation: 966

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

I'm looking at some 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);

On some environments the last line works, and on others it throws an Unparseable date exception. It looks like on some systems the default date format is 2013-01-25 00:00:00.0, and on others 2013-01-25 00:00:00. The JVM, OS and Oracle version are different between the environments (all use Oracle and run on a unix variant though).

Changing the code might be complex. I'm wondering if there is an environment variable or similar that can be set to make the date format returned from rs.getString() consistent?

Upvotes: 6

Views: 47523

Answers (4)

Barney
Barney

Reputation: 2836

For the Oracle JDBC driver I am using, the format is hard-coded in the driver library, so should only differ across systems if different driver versions are in use.

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

(Apologies for asking a separate question, but as your question had been answered multiple times with the ever-helpful "just don't do that" response, I tried again...).

Upvotes: 0

Arpit
Arpit

Reputation: 12797

try this:

ResultSet rs = ps.executeQuery();

Date myDate = rs.getDate("MY_DATE"); 

or this :

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

More about 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

Upvotes: 4

ddewaele
ddewaele

Reputation: 22603

Instead of using

String myDateStr = rs.getString("MY_DATE") 

you should use

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

JDBC / Database will handle the date transformation for you.

Upvotes: 3

Jim Garrison
Jim Garrison

Reputation: 86774

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

Upvotes: 2

Related Questions