I'm having some trouble trying to use timestamp2 instead of Timestamp in SQL Server 2008. Apparently, rs.getTimestamp has very different behavior between timestamp and timestamp2. However, I can't find any documentation stating that there should be a difference, or that I should be using something different. I wonder whether I'm just doing something wrong.
Environment:
- Tried on both SQL Express 2008 (10.0) and SQL Server 2008 R2 (10.5).
- sqljdbc4.jar version 3.0, size of 537,303 bytes, CRC-32=a0aa1e25, MD5=402130141d5f2cee727f4371e2e8fd8a.
- Java 1.6
Here is a unit test demonstrating the problem. The only "magic" is the "Db.getConnection()", which you can replace with appropriate code. The test is the same for both datetime and datetime2, but the datetime2 test fails with a date that is 2 days prior. I treat all times in the DB as GMT/UTC, and I haven't attempted to add timezone information into the database data for datetime2 data.
private void testTimestamp(TimeZone gmtTz, Connection conn, String query,
Calendar expectedCal) throws SQLException
{
PreparedStatement stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
// Note the expectedCal has a GMT timezone.
Date actualTs = rs.getTimestamp("dt", expectedCal);
// Just print out the time difference
long diff = actualTs.getTime() - expectedCal.getTimeInMillis();
System.out.println("Diff=" + diff);
// Do the test to make sure they are the same
// In practice, this succeeds for datetime and fails for datetime2
Assert.assertEquals(expectedCal.getTimeInMillis(), actualTs.getTime());
}
}
@Test
public void testDateTime() throws SQLException
{
Connection conn = Db.getConnection();
TimeZone gmtTz = TimeZone.getTimeZone("GMT");
String query;
Calendar expectedCal = Calendar.getInstance(gmtTz);
expectedCal.clear();
expectedCal.set(2011, 10, 02, 11, 17);
query = "select CAST('2011-11-02 11:17:00' as datetime) as dt";
testTimestamp(gmtTz, conn, query, expectedCal);
query = "select CAST('2011-11-02 11:17:00.0000000' as datetime2) as dt";
testTimestamp(gmtTz, conn, query, expectedCal); // results in an error
}
Is my only option switching back to timestamp?
EDIT: For future Googlers, using sqljdbc4.jar version 3.0, the test fails on Linux, but passes on Windows. I have not yet tried sqljdbc4.jar version 4.0 that comes with SQL Server 2012.