将服务器时间设置为本地时间

时间:2015-05-22 13:05:28

标签: java sql

我将到货时间数据存储在openshift服务器上。服务器时间和当地时间之间有6个小时的差异,因此我尝试将服务器时间设置为当地时间,以便在请求中获得正确的arrivaltime。如果我删除preparedTime.setTime(2, time); preparedTime.setTime(3, time);并在SQL中设置outcommenting行,它就可以工作。

我感谢任何帮助。

String day = "";
switch (WDay) {
case 7:
    day = "sat";
    break;
case 1:
    day = "sun";
    break;
default:
    day = "mon-fri";

}

String sql = "SELECT route FROM arrivaltimes INNER JOIN stops"
        + " ON arrivaltimes.stop_id = stops.stop_id"
        + " WHERE weekday = ?" 
        //+ "and arrivaltime BETWEEN curtime() - INTERVAL 2 MINUTE AND curtime() + INTERVAL 2 MINUTE"
        + "and arrivaltime BETWEEN ? - INTERVAL 2 MINUTE AND ? + INTERVAL 2 MINUTE"
        + " and name LIKE ?";
PreparedStatement preparedTime = con.prepareStatement(sql);

Calendar cal = Calendar.getInstance();
TimeZone timeZone = TimeZone.getTimeZone("Europe/Berlin");
calendar.setTimeZone(timeZone);

preparedTime.setString(1, day);

Time time = new Time(cal.getTime().getTime());
preparedTime.setTime(2, time);
preparedTime.setTime(3, time);
preparedTime.setString(4, stopName);

ResultSet rsArrivaletime = preparedTime.executeQuery();

到达时间表:

    stt.execute("CREATE TABLE IF NOT EXISTS arrivaltimes(arrivaltimes_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,"
            +  " weekday VARCHAR(20) NOT NULL,"
            + "route INT(11) NOT NULL, "
            + "arrivaltime time NOT NULL,"
            + " stop_id INT, FOREIGN KEY fk_stop_id(stop_id) REFERENCES stops(stop_id) )" );

1 个答案:

答案 0 :(得分:1)

我认为正确的方法是将所有内容存储在UTC中,并仅在用户输入输出期间将这些UTC时间戳转换为应用程序中的本地时间。

以下是java中时区使用的教程:http://tutorials.jenkov.com/java-date-time/java-util-timezone.html