Get a Date for a Specific Time Zone : Date Time Timestamp « Database « Java Tutorial






import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Calendar;
import java.util.TimeZone;

public class Main {
  public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement();

    st.executeUpdate("create table survey (id int,myDate DATE );");
    String INSERT_RECORD = "insert into survey(id, myDate) values(?, ?)";

    PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);
    pstmt.setString(1, "1");
    java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
    pstmt.setDate(2, sqlDate);

    pstmt.executeUpdate();

    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    Calendar cal = Calendar.getInstance();

    // get the TimeZone for "America/Los_Angeles"
    TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
    cal.setTimeZone(tz);

    while (rs.next()) {
      // the JDBC driver will use the time zone information in
      // Calendar to calculate the date, with the result that
      // the variable dateCreated contains a java.sql.Date object
      // that is accurate for "America/Los_Angeles".
      java.sql.Date dateCreated = rs.getDate(2, cal);
      System.out.println(dateCreated);
    }

    rs.close();
    st.close();
    conn.close();
  }

  private static Connection getConnection() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");
    String url = "jdbc:hsqldb:mem:data/tutorial";

    return DriverManager.getConnection(url, "sa", "");
  }
}








20.20.Date Time Timestamp
20.20.1.Working with Date, Time, and Timestamp in JDBC
20.20.2.Insert Date value
20.20.3.Get Date value from ResultSet
20.20.4.Insert TIME value
20.20.5.Get TIME value from ResultSet
20.20.6.Insert TIMESTAMP value
20.20.7.Get TIMESTAMP value from ResultSet
20.20.8.Get the Current Date as a java.util.Date Object
20.20.9.Creating java.sql.Date Using java.util.Date
20.20.10.Creating java.sql.Date Using java.util.Calendar
20.20.11.Creating java.sql.Date Using the java.sql.Date.valueOf() Method
20.20.12.Creating java.sql.Date Using GregorianCalendar
20.20.13.Getting a Timestamp Object Using java.util.Date
20.20.14.Getting a Timestamp Object Using System.currentTimeMillis()
20.20.15.Get the Current Timestamp as a java.sql.Time Object?
20.20.16.Convert a String Date Such as 2003/01/10 to a java.sql.Date Object?
20.20.17.Convert a Timestamp to Month-Day-Year
20.20.18.Get a Date Label from a java.sql.Timestamp Object
20.20.19.Convert a java.sql.Timestamp Object to a java.util.Date Object?
20.20.20.Make a java.sql.Timestamp Object for a Given Year, Month, Day, Hour
20.20.21.Get a Date for a Specific Time Zone
20.20.22.Returns a java.sql.Timestamp equal to the current time
20.20.23.Convert into java.sql.Time into java.util.Calendar