Java ResultSet.getTimestamp()将毫秒附加到输出

时间:2015-09-08 10:22:07

标签: java postgresql timestamp

我的表格timestamptest包含timestamp类型的单个列timestamp without time zone

我在此表中插入了一个值:
insert into timestamptest values('2015-09-08 13:11:11')

时间戳不包含任何毫秒值。
在pgAdmin中选择此数据时,显示与上面相同。

但是当我使用jdbc连接获取此数据时,显示的值为毫秒。

    Class.forName("org.postgresql.Driver");
    Connection lConnection = null;
    lConnection = DriverManager.getConnection(
       "jdbc:postgresql://localhost:5432/postgres","postgres", "Password@123");
    String lQuery = "select * from timestamptest";
    Statement lStatement = lConnection.createStatement();
    ResultSet lResultSet = lStatement.executeQuery(lQuery);
    while(lResultSet.next()) {
        System.out.println(lResultSet.getTimestamp(1));
    }

输出:2015-09-08 13:11:11.0

所需的输出为2015-09-08 13:11:11

可以通过使用SimpleDateFormat来实现:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(lResultSet.getTimestamp(1).getTime())

不使用SimpleDateFormat可以吗?结果集本身是否以其他方式为我提供了所需的格式?

我需要的是声明 lResultSet.getTimestamp(1)
直接给我输出2015-09-08 13:11:11

2 个答案:

答案 0 :(得分:0)

不可能。由于ResultSet.getTimestamp(1)返回扩展java.sql.TimeStamp的类。基于数据库驱动程序返回类。而且我们也无法改变toString的实施。

答案 1 :(得分:0)

是的,你可以 - 但你不会喜欢它。

class MyTimestamp extends Timestamp {

    public MyTimestamp(long time) {
        super(time);
    }

    public MyTimestamp(Timestamp ts) {
        this(ts.getTime());
    }

    @Override
    public String toString() {
        String s = super.toString();
        return s.substring(0, s.lastIndexOf("."));
    }
}

public void test() {
    System.out.println("Hello");
    Timestamp t = new Timestamp(System.currentTimeMillis());
    System.out.println(t);
    System.out.println(new MyTimestamp(t));

}