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

走远了吗. 提交于 2021-01-28 00:00:45

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/33156923/java-resultset-getstring-for-date-field-displaying-000000-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!