3

I have a problem when getting a Date object from a ResultSet. In database it has a value (for example 2014-08-01) and after getting it from resultSet, it has another value (2014-08-31). I know that ResultSet's getDate method returns java.sql.Date, but I tried a few solutions, such as:

Date date=new java.util.Date(resultSet.getDate(3).getTime());

or

Date date=resultSet.getTimestamp();

but the problem was the same. If I try

Date date=resultSet.getDate();

It throws a NullPointerException.

Can anybody explain this?

user3836820
  • 33
  • 1
  • 1
  • 3
  • 1
    You have to specify the column index or name, `Date date=resultSet.getDate(3);` or `Date date=resultSet.getDate("DATE_COLUMN");` – Elliott Frisch Jul 14 '14 at 12:34
  • The [question here](http://stackoverflow.com/q/5160064/2144390) looks like it might be related. Does its answer help you? – Gord Thompson Jul 14 '14 at 12:40
  • Just to clarify: Is the "another value" really 2014-08-31 (30 days later) or is it actually 2014-07-31 (the previous day)? – Gord Thompson Jul 14 '14 at 14:23
  • It is 2014-08-31, 30 days later – user3836820 Jul 14 '14 at 16:31
  • 1
    What *exactly* is the data type of the column? And confirm this is MySQL as the tag indicates. What *exactly* is the value you input, the value you expected to extract, and the value tha surprised you? Exactly what code did you write to to the INSERT and the SELECT? – Basil Bourque Jul 14 '14 at 18:39

2 Answers2

13

In your case you were not providing the columnName of the Date field to be retrieved.

This should do the job

 while (rs.next()) {
    java.sql.Time dbSqlTime = rs.getTime("columnName");
    java.sql.Date dbSqlDate = rs.getDate("columnName");
    java.sql.Timestamp dbSqlTimestamp = rs.getTimestamp("columnName");     
    java.util.Date dbSqlTimeConverted = new java.util.Date(dbSqlTime.getTime());
    java.util.Date dbSqlDateConverted = new java.util.Date(dbSqlDate.getTime());
    System.out.println(dbSqlTimeConverted);
    System.out.println(dbSqlDateConverted);
 }

iterate over the ResultSetObject get the Date from the ResultSetObject which is java.sql.Date then convert it to java.util.Date

SparkOn
  • 8,806
  • 4
  • 29
  • 34
  • 2
    I find it strange that this is the accepted answer. Not providing the column name would result in a compile time error (as there is no overload that doesn't take a parameter), not in wrong dates, nor would it lead to a `NullPointerException` – Mark Rotteveel Jul 15 '14 at 07:20
2

You should use the java.sql.Date instead of java.util.Date, because ResultSet.getDate() returns an SQL Date, and not a Java one.

tashuhka
  • 5,028
  • 4
  • 45
  • 64
loloreyn
  • 31
  • 2