Why Time gets truncated with ResutSet getDate() function.

Recently I stuck in an issue on populating date from stored procedure. I am reading a date from a resultset using rs.getDate(), storing in a java.util.Date instance variable and displaying on the screen.

Java.util.Date  mydate = rs.getDate(1);

Output is only date while time is truncated.  But why …!
That confused me a lot. So I google it. Spending lot of time in reading blogs, oracle docs and trying different things on oracle server like checking  NLS_DATE_FORMAT, I am not able to get the time.
Next I come across a Timestamp thing in Resultset class.

Rs.getTimestamp (int colIndex)

When I use it, I immediately get the time.  Now, the important question, why the resultset function getDate() does not return the Time. Now my search is preety narrow. What I found is :-

In java, we have java.util.Date for java.sq.Date . So functionalities available in sql.Date are also available in util.Date. But there is one difference, sql.Date stores only Date and not Time of date. To get the time, we have to use java.sql.Timestamp class. We can store into util.Date object since Timestamp, in both java.util and java.sql , extends Date class of respective packages.

To verify, I ran the following simple program which verifies my explanation.

public class DateProb {        

       public static void main(String[] args) {

              long time = System.currentTimeMillis();
              java.sql.Date sqlDate = new java.sql.Date(time);
              System.out.println(sqlDate);
              java.sql.Timestamp timestamp = new java.sql.Timestamp(time);
              System.out.println(timestamp);
              java.util.Date utilDate = new java.util.Date(time);
              System.out.println(utilDate);     
       }       
}

Output:-

2012-02-06
2012-02-06 22:33:36.946
Mon Feb 06 22:33:36 IST 2012

Please share your thoughts on this.

Comments

  1. This is not exactly true...
    I don't get this, but belive me it happened: I had a class Record, having 7 fields, one of them was java.util.Date. I used no ORM, so I had a RowMapper with ResultSetExtractor. The thing is, that I used getDate() and received date and time. After adding one more field to the entity, the getDate function started to return only date.
    Can anybody explain it?

    ReplyDelete
  2. Hi Maciek, Can you please check the imports and can you post the code.

    ReplyDelete

Post a Comment

Popular posts from this blog

When to use getClass() and instanceOf in Java

How class.forName loads the Database Driver in JDBC