Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ResultSet.getString() for Date field displaying 00:00:00.0

I am using a generic method to loop through and convert a ResultSet to a String array. I am wondering why does the Date column in Oracle db value come print out as 2015-01-09 00:00:00.0 while the date in the database shows 2015-01-09 ?

Here is the code, the col type in Oracle is Date

    while(rs.next()) {
        String[] arr = new String[colCount];
        for(int i = 1; i <= colCount; i++) {
            arr[i-1] = rs.getString(i);
        }//end for
        list.add(arr);
    }//end while

So that is part 1 of the question, part 2 of the question - is my best option for a generic method here to do a .replace 00:00:00.0 to remove that?

like image 697
Kairan Avatar asked Sep 01 '26 22:09

Kairan


1 Answers

You shouldn't be using rs.getString() on a Date datatype. You should be using rs.getDate() and then parse the date as you wish.

Example:

java.sql.Date date = rs.getDate(i);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = dateFormat.format(date);

Or you can directly get date as string directly from the database using the TO_CHAR function like this:

SELECT TO_CHAR(col1, 'yyyy-mm-dd') AS 'MYDATE' FROM TABLE1;

And then get it as string:

String dateStr = rs.getString("MYDATE");

Hope this helps

like image 53
MaVRoSCy Avatar answered Sep 03 '26 13:09

MaVRoSCy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!