Return extra ".0" when reading "smalldatetime" column with PreparedStatement

181 Views Asked by At

I have a table in SQL Server with a column type smalldatetime and I am using PreparedStatement to read/write data in my tables. E.g My table is like:

|         date           |
+------------------------+
|   2019-11-06 09:48:00  +
|   2019-11-05 07:04:00  +
|         ...            +
+------------------------+

and I am reading the column date with:

String date = rs.getString("date");

And I get an extra .0 at the end of the date:

2019-11-06 09:48:00.0
2019-11-05 07:04:00.0

Why is this happening?

1

There are 1 best solutions below

1
On BEST ANSWER

The underlying SQL Server JDBC driver converts the returned bytes into a GregorianCalendar first and then calls toString on a newly created Timestamp based on this GregorianCalendar. This causes the trailing .0.

case CHARACTER: {
  ...many other conversions...
  switch (ssType) {
    case DATETIME: // and SMALLDATETIME
    {
      return (new java.sql.Timestamp(cal.getTimeInMillis())).toString();
    }

mssql-jdbc Conversion Code mssql-jdbc SMALLDATETIME handling

So what the mssql-jdbc code actually executes is:

System.out.println(new java.sql.Timestamp(100).toString());

> 1970-01-01 00:00:00.1

JavaDoc Timestamp#toString