简体   繁体   中英

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?

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

The Oracle DATE datatype contains both a date and a time. So this isn't weird -- it is Oracle.

I would personally convert the date to a java.sql.Date to remove the trailing time. You can use the ResultSet.getDate() method for this.

See the docs on this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM