Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jdbc

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?

like image 823
Tim Avatar asked Feb 05 '13 05:02

Tim


People also ask

What is the default type of ResultSet in JDBC application?

The default ResultSet type is TYPE_FORWARD_ONLY . Note: Not all databases and JDBC drivers support all ResultSet types. The method DatabaseMetaData.

How do you find the ResultSet of a date?

Execute the query using the executeQuery() method. Pass the select query to retrieve data (String) as a parameter to it. From the obtained result set object get the date value (along with other values) using the getDate() method of the ResultSet interface.

What is JDBC connection Statement and ResultSet?

The SELECT statement is the standard way to select rows from a database and view them in a result set. The java. sql. ResultSet interface represents the result set of a database query. A ResultSet object maintains a cursor that points to the current row in the result set.

What is Java SQL date?

A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT. To conform with the definition of SQL DATE , the millisecond values wrapped by a java. sql.


2 Answers

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

like image 117
Arpit Avatar answered Sep 28 '22 08:09

Arpit


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.

like image 31
ddewaele Avatar answered Sep 28 '22 08:09

ddewaele