Java JDBC: dates consistently two days off

前端 未结 9 1860
孤城傲影
孤城傲影 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());
    

提交回复
热议问题