Java JDBC: dates consistently two days off

前端 未结 9 1798
孤城傲影
孤城傲影 2020-12-14 16:53

I am using Java JDBC to write a date to SQL server 2008 and then read it back.
The date that is read back is consistently two days earlier than the date that was actuall

相关标签:
9条回答
  • 2020-12-14 17:09

    Your problem is Time Zone values ("GMT").
    You need to introduce this manipulation in your JDBC fetching method as follows:

    Calendar gmt = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    PreparedStatement stmt = connection.prepareStatement(sql);
    stmt.setDate(1, new Date(0)); // I assume this is always GMT
    ResultSet rs = stmt.executeQuery();
    rs.next();
    
    //This will output 0 as expected
    System.out.println(rs.getDate(1, gmt).getTime());
    
    0 讨论(0)
  • 2020-12-14 17:10

    This issues is coming when we are using date DataType in Microsoft sql. I have fixed this to change date to datetime.

    0 讨论(0)
  • 2020-12-14 17:11

    If you are using MSSQL 2015, use this Sqljdbc41 to fix this issue

     <!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/sqljdbc41 -->
    <dependency>
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>sqljdbc41</artifactId>
        <version>6.0.8112</version>
    </dependency>
    
    0 讨论(0)
提交回复
热议问题