Is java.sql.Timestamp timezone specific?

后端 未结 6 1467
忘掉有多难
忘掉有多难 2020-11-22 04:51

I have to store UTC dateTime in DB.
I have converted the dateTime given in specific timezone to UTC. for that I followed the below code.
My input dateTime is \"20121

6条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 05:16

    For Mysql, we have a limitation. In the driver Mysql doc, we have :

    The following are some known issues and limitations for MySQL Connector/J: When Connector/J retrieves timestamps for a daylight saving time (DST) switch day using the getTimeStamp() method on the result set, some of the returned values might be wrong. The errors can be avoided by using the following connection options when connecting to a database:

    useTimezone=true
    useLegacyDatetimeCode=false
    serverTimezone=UTC
    

    So, when we do not use this parameters and we call setTimestamp or getTimestamp with calendar or without calendar, we have the timestamp in the jvm timezone.

    Example :

    The jvm timezone is GMT+2. In the database, we have a timestamp : 1461100256 = 19/04/16 21:10:56,000000000 GMT

    Properties props = new Properties();
    props.setProperty("user", "root");
    props.setProperty("password", "");
    props.setProperty("useTimezone", "true");
    props.setProperty("useLegacyDatetimeCode", "false");
    props.setProperty("serverTimezone", "UTC");
    Connection con = DriverManager.getConnection(conString, props);
    ......
    Calendar nowGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    Calendar nowGMTPlus4 = Calendar.getInstance(TimeZone.getTimeZone("GMT+4"));
    ......
    rs.getTimestamp("timestampColumn");//Oracle driver convert date to jvm timezone and Mysql convert date to GMT (specified in the parameter)
    rs.getTimestamp("timestampColumn", nowGMT);//convert date to GMT 
    rs.getTimestamp("timestampColumn", nowGMTPlus4);//convert date to GMT+4 timezone
    

    The first method returns : 1461100256000 = 19/04/2016 - 21:10:56 GMT

    The second method returns : 1461100256000 = 19/04/2016 - 21:10:56 GMT

    The third method returns : 1461085856000 = 19/04/2016 - 17:10:56 GMT

    Instead of Oracle, when we use the same calls, we have :

    The first method returns : 1461093056000 = 19/04/2016 - 19:10:56 GMT

    The second method returns : 1461100256000 = 19/04/2016 - 21:10:56 GMT

    The third method returns : 1461085856000 = 19/04/2016 - 17:10:56 GMT

    NB : It is not necessary to specify the parameters for Oracle.

提交回复
热议问题