java - 为什么这个 SimpleDateFormat 丢失了时间信息?

标签 java simpledateformat

我有这个处理 ResultSet 的 Java 方法。

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]);
    }
}

如您所见,所有结果都被视为字符串类型(无论列类型是什么,都使用 getString)。当遇到 Date 列时,它会自动转换为 String。结果日期将与此类似:

2012-08-01 16:10:47.0

我修改了上面的脚本,创建了类似的东西:

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;
        }   
    }
}

此方法将所有内容都视为对象,之后将检查该对象是否是 Date 的实例。如果这是真的,它将根据 formatter 进行格式化。问题是这样返回的数据是这样的:

2012-08-01 00:00:00.0

为什么?

更新 1 - 最后的工作方法实现:

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] = "";
        }       
    }
}

最佳答案

java.sql.Date不存储有关时间的信息:

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.

关于java - 为什么这个 SimpleDateFormat 丢失了时间信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13472993/

相关文章:

java - 简单的日期格式年份格式问题

java.text.ParseException : Unparseable date: "20:01:00.000Z"

java - Java 8 SimpleDateFormat 中可能存在错误?

java - 何时在 JMS 中使用同步和异步消息?

java - 当我尝试从 JList 到另一个 JList 的 getSelectedValue() 时出现错误

java - 将取消按钮添加到自定义警报对话框

java - 如何解析具有个位数偏移量的时区? "Wed Dec 31 00:00:00 GMT-8 1969"

java - 如何将 JDateChooser 格式化为 dd-mm-yyyy?

Java 11 不可变映射 : create Map. 条目

java - 使用 IntelliJ 远程调试 jnlp 应用程序