当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Why this SimpleDateFormat lost info about time?

问题描述:

I have this Java method that process a ResultSet.

protected void populateDto(String[] rowSet, ResultSet rs, String[] columunsNames) throws SQLException {

for (int i = 0; i < rowSet.length; i++) {

rowSet[i] = rs.getString(columunsNames[i]);

}

}

As you can see all result are treated as String type (getString is used whatever is the column type). When a Date column is encountered it is automatically converted into a String. The resulting date will appear similar to this one:

2012-08-01 16:10:47.0

I have modified the above script, creating something like that:

protected void populateDto(String[] rowSet, ResultSet rs, String[] columunsNames) throws SQLException {

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

for (int i = 0; i < rowSet.length; i++) {

Object o = rs.getObject(columunsNames[i]);

if (o instanceof Date) {

rowSet[i] = formatter.format((Date)o);

} else {

rowSet[i] = (String)o;

}

}

}

This method treat everything as Object, after, will check if that Object is an instance of Date. If this is true it will formatted in according to the formatter. The problem is that in this way the data returned is like:

2012-08-01 00:00:00.0

Why?

Update 1 - Last working method implementation:

protected void populateDto(String[] rowSet, ResultSet rs, String[] columunsNames, SimpleDateFormat formatter) throws SQLException {

Timestamp ts = null;

for (int i = 0; i < rowSet.length; i++) {

Object obj = rs.getObject(columunsNames[i]);

if (obj instanceof Date) {

ts = rs.getTimestamp(columunsNames[i]);

rowSet[i] = formatter.format(ts);

} else {

if(obj!=null)

rowSet[i] = obj+"";

else

rowSet[i] = "";

}

}

}

网友答案:

This method treat everything as Object, after, will check if that Object is an instance of Date.

Instead of date use java.sql.Timestamp, with this you can get Date as well as Time either you persist data or fetch data.

Update 1

You can have a general method like

public Timestamp getTimestamp(int columnIndex) throws SQLException {
    Object value = getObject(columnIndex);
    if (value instanceof Timestamp) return (Timestamp) value;

  }

this will return the date and time and you could call by passing the column index.

网友答案:

java.sql.Date does not store info about time:

To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.

分享给朋友:
您可能感兴趣的文章:
随机阅读: