Timezones in SQL DATE vs java.sql.Date

后端 未结 7 781
天涯浪人
天涯浪人 2020-11-28 04:11

I\'m getting a bit confused by the behaviour of the SQL DATE data type vs. that of java.sql.Date. Take the following statement, for example:



        
7条回答
  •  爱一瞬间的悲伤
    2020-11-28 05:05

    There is an overload of getDate that accepts a Calendar, could using this solve your problem? Or you could use a Calendar object to convert the information.

    That is, assuming that retrieval is the problem.

    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());
    

    Alternatively, assuming that storage is the problem.

    Calendar gmt = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    PreparedStatement stmt = connection.prepareStatement(sql);
    gmt.setTimeInMillis(0) ;
    stmt.setDate(1, gmt.getTime()); //getTime returns a Date object
    ResultSet rs = stmt.executeQuery();
    rs.next();
    
    //This will output 0 as expected
    System.out.println(rs.getDate(1).getTime());
    

    I don't have a test environment for this, so you will have to find out which is the correct assumption. Also I believe that getTime returns the current locale, otherwise you will have to look up how to do a quick timezone conversion.

提交回复
热议问题